Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics Help  RSS feed

 
Ste Graham
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm just in the process of re-coding some classes for java 1.5. They all compiled and worked fine under 1.4, but Im getting compile warnings under 1.5 (even though they still all run correctly). I'm new to Jave 1.5, and it appears that the issue I am having is with generics. I have a class which holds the following ArrayList:

ArrayList records = new ArrayList();

Obviosuly, I get an "unchecked" warning when compiling this, so I do:

ArrayList<Integer> records = new ArrayList<Integer>();

Further on in the code I want to add this ArrayList to another ArrayList, so I try:

ArrayList keepRecords = new ArrayList(records);

Again I get an unchecked warning, so I do:

ArrayList<ArrayList> keepRecords = new ArrayList<ArrayList>(records);

I htink this is correct, because keepRecords is an ArrayList that contains other ArrayLists. However, when i compile I get:



As far as I can see this should be correct. In 1.4 I could create an ArrayList with a another Collection (e.g. An ArrayList),and it worked fine. No matter what I try I can't get this to work. Any help would be much appreciated!

Stephen :-)
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Stephen,

depends on what you want to achieve:

you wrote December 05, 2006 03:09 AM
Further on in the code I want to add this ArrayList to another ArrayList, so I try (...)


If you want to add the content of records to another ArrayList, the must have the same type:
ArrayList<Integer> records = new ArrayList<Integer>();
ArrayList<Integer> keepRecords1 = new ArrayList<Integer>(records);
They must have the same type.

But if you want to have an ArrayList that stores ArrayLists of type Integer, you'd write:
ArrayList<ArrayList<Integer>> keepRecords2 = new ArrayList<ArrayList<Integer>>();
keepRecords2.add(records);


Looks a bit weird if you look at it in the first place, but compiles and runs without warning or exception.
I think, what you wanted was the second case.

Yours,
Bu.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!