Jump to content

No output on simple code: learning ArrayList class

- - - - -

  • Please log in to reply
3 replies to this topic

#1
scottbomb

scottbomb

    Newbie

  • Members
  • PipPip
  • 21 posts
I'm learning ArrayList (in a chapter on Generics) but I can't get this simple code to output anything. I understand there are differences between the regular array syntax of [] vs. the ArrayList class. The chapter (Absolute Java, ed. 4) doesn't address loops but from what I've read, it seems this should work.

The compiler reports no errors, yet the output is completely blank and I'm stumped. I've tried it with a regular for loop and a for-each (both shown below) and neither outputs anything. Can anyone see what I'm missing?


import java.util.ArrayList;


 public class ArrayListTest

 {

 	public static void main(String[] args)

 	{

 		ArrayList<Double> someArray = new ArrayList<Double>(20);

		for (int i = 0; i < someArray.size(); i++)

			someArray.add(i + 0.5);


		for (int i = 0; i < someArray.size(); i++)

			System.out.print(someArray.get(i) + ", "); // prints out 0.5, 1.5, 2.5 ... 20.5


		System.out.println(); // to add a carriage return and blank line


		for (Double x : someArray)

			System.out.print(x + ", "); // prints out 0.5, 1.5, 2.5 ... 20.5

 	}

 }



#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
.size() does this according to javadoc:

Quote

Returns the number of elements in this list.
So that's 0, meaning you never add anything to the list.

You can't access the arrayList's capacity. Just hardcode 20, or put 20 in a variable and use it 2 times.
Well, in theory you could go dig into your object using reflection to access private fields and get the capacity that way. But that's fighting with OOP and won't be better than using a variable.

#3
Sinipull

Sinipull

    Programming Expert

  • Members
  • PipPipPipPipPipPip
  • 386 posts
Yes, you do not have to declare initial capacity of the ArrayList manually, because it will increase the capacity by double every time it starts to fill up. ( new ArrayList() is good enough) Although giving it an argument is usually good idea for efficiency, if you know your ArrayList will be filled with thousands of elements for example.

In your case it only confused you, because you thought that ArrayList works like an array, returning the whole capacity(20), but instead it returns only the number of elements actually inside of it(0).

#4
scottbomb

scottbomb

    Newbie

  • Members
  • PipPip
  • 21 posts
Right on! Thanks so much guys.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users