+ 1

Trouble calling an ArrayList length to to make a boolean argument.

What am I missing when I try to write these lines to call an ArrayList length to make a boolean argument based on how many Integers are in the ArrayList. import java.util.Scanner; import java.util.ArrayList; import java.util.List; public class PairCalc { public static void main(String[] args) { Scanner rawinput = new Scanner(System.in); List<Integer> arraynumbers = new ArrayList<>(); for(String num: rawinput.nextLine().split("-")) { arraynumbers.add(Integer.parseInt(num)); System.out.println(num); } System.out.println(arraynumbers); System.out.println(arraynumbers.length); if(arraynumbers.length == (1)) { //these are the 2 lines that stump me. System.out.println(arraynumbers.length); } //} /*int x = (arraynumbers.get(0) - 1)*150 + (arraynumbers.get(1)*6) - 6 + (arraynumbers.get(2)); System.out.println("Your Pair = " + x);*/ } } my goal is to do something different if there is only one int in the arraylist. Thanks for any guidance.

5th Sep 2017, 3:16 AM
87yj
87yj - avatar
3 ответов
+ 2
Arrays don"t have a public length variable. Instead they have the size() method. Which is sort of the same thing. (The amount of elements in the array). Like so: if(arraynumbers.size() == 1)
5th Sep 2017, 4:07 AM
Rrestoring faith
Rrestoring faith - avatar
+ 1
Bingo!! that was it! I kept trying to use .length I've learned 2 things about the ArrayList this week. 1. they will automatically add the amount of items with a for loop. for(String num: rawinput.nextLine().split("-")) { arraynumbers.add(Integer.parseInt(num)); System.out.println(num); } 2. they do not have a .length but instead .size. if(arraynumbers.size() == 1) { System.out.println(arraynumbers.size()); } Thanks so much for the help.
5th Sep 2017, 4:23 AM
87yj
87yj - avatar
+ 1
Hey 87yj,I can explain this for you.To ArrayList, you need to know the differences among "capacity, length and size",capacity equals to length, think about that you have a box of eggs.,the box's name is ArrayList.The box can put 12 eggs in it.Its capacity(length) is 12, but you only have 10 eggs in it,at this time, its size is 10. Capacity = array.length >= array.size.while if there is no unused cells available,the array will expend,1.5times larger by default.
5th Sep 2017, 4:24 AM
Ran
Ran - avatar