Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Strings to an ArrayList [closed]

I need to make sure I am building this program right. I have to write a program that uses an ArrayList container and put 5 Strings in it and then print out the 5 Strings from the ArrayList. I am new to ArrayList's so want to make sure I have the requirements fulfilled.

My question is: "Is this the proper way to Create Strings, Create an ArrayList, add the Strings to the List and then Print the List?"

public static void main(String[] args) 
{

ArrayList<String> names_and_numbers = new ArrayList<>();
String bob = "bob";
String nancy = "nancy";
String jim = "jim";
String claire = "claire";

names_and_numbers.add( bob ); 
names_and_numbers.add( nancy ); 
names_and_numbers.add( jim );
names_and_numbers.add( claire );      

for (String e : names_and_numbers)  
{  
 System.out.println(e);  
} 

int six = 6;
String numbers = "";

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

myList.add( 1 ); 
myList.add( 2 ); 
myList.add( 3 );
myList.add( 4 );
myList.add( 5 );
myList.add(six);        

for (int x : myList)  
{  
 System.out.println(x);  
}     

//System.out.println(myList);   
//System.out.println(names_and_numbers);   
}
}

1 Answers

You're doing ok, I don't see a question but I think that arraylists store objects, so if you want an integer, get build an object. I guess if you can compli that, this is done automatically.

Integer i = new Integer(1);
myList.add(i);

Or in 1 line

myList.add(new Integer(1));

Edit:

As Paul Bellora says, new Integer(i) is unnecessary and you can replace it with just i. I just wanted to point out that ArrayLists store objects (somehow i forgot to mention that), not primitive data types like int and when you try to do it, the data is converted if possible (to the compiler) to a child of Object just like Integer.

like image 189
Roger Avatar answered Aug 26 '26 13:08

Roger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!