-2

I wish to store some phone number in arraylist and if the number contain leading zero ,i want to store in arraylist as it is, without removing leading zero. how can i achieve that .

ArrayList<Integer> Restrict = new ArrayList<Integer>();
cars.add(01);
cars.add(02);
cars.add(3);
cars.add(4);
System.out.println(cars.get(0));

output

1      

how can i get 01 instead of 1.

tomtom
  • 268
  • 1
  • 14

2 Answers2

3

You can store them as strings

ArrayList<String> Restrict = new ArrayList<>();
        cars.add("01");
        cars.add("02");
        cars.add("3");
        cars.add("4");

    System.out.println(cars.get(0));
1

Integer is the wrong type for this requirement

A phone number consists of a minimum of 10 digits (first digit from 1-9) and it can go well beyond the maximum limit of Integer which is 2147483647.

Apart from this, the 0 at the beginning of an Integer means it's radix is 8 i.e. it represents an octal number e.g.

public class Main {
    public static void main(String[] args) {
        int x = 0123;
        System.out.println(x);
    }
}

Output:

83

Note that (0123)8 = (83)10

The right type for this requirement is String i.e. you should declare your List as follows:

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

and store the numbers as

restrict.add("01234567890")
restrict.add("1234567890")

Also, always follow the Java naming conventions e.g. the name of the variable can be restrict but should not be named as Restrict (as in your code).

Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72
  • While this is a good answer, I can't help but feel your effort is misplaced – Michael Nov 20 '20 at 11:36
  • @Michael - Thanks for the feedback. No worries, I posted it anyway because I was half-way while this was closed. If it can be helpful for anyone, that's the best reward I will have for this effort. – Arvind Kumar Avinash Nov 20 '20 at 11:39