• 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
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Java Collections

 
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
import java.util.*;

public class Test {

public static void main(String[] args) {

List x = new ArrayList<String>();
x.add("Hello");
x.add(new Integer(5));
}


}

Though the type of ArrayList mark as String it accepts Integers.How ?
 
Bartender
Posts: 4116
72
Mac TypeScript Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Aruna Balasuriya wrote:....
Though the type of ArrayList mark as String it accepts Integers.How ?


Hi Aruna, Welcome to JavaRanch

Though it compiles you get an unchecked warning as the compiler looks at the reference type which is of List (raw type) hence not able to do the type checking.
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey..

Are you expecting an error?

You have used List x = new ArrayList<String>(); which means the list x can accept element of any datatype. If you specifically want to add elements of string type then you have to modify it as:


List<String> x = new ArrayList<String>();
 
Ranch Hand
Posts: 237
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Aruna Balasuriya wrote:
List x = new ArrayList<String>();



It should look like this,

List<String> x = new ArrayList<String>();

Otherwise x is a "raw" List and you can enter any object.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic