• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Generics Help

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 :-)
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic