0

I create Vector and I want add Integer in vector. but "new Integer()" have error.

Vector<Integer> intergers = new Vector<Integer>();
intergers.add(new Integer());

what can i do?

  • now i use "Integer" & parameter like "new Integer(0)" but "new Integer(0)" have yellow underline. what can i do to remove this line?

  • ok, why The constructor Integer(int) is deprecated since version 9?

  • ok! i found why.

"It is rarely appropriate to use this constructor. The static factory valueOf(int) is generally a better choice, as it is likely to yield significantly better space and time performance."

https://docs.oracle.com/javase/9/docs/api/java/lang/Integer.html

thx all

Super Shark
  • 376
  • 3
  • 12

4 Answers4

4

You should use "Integer", not "Interger". Moreover, Integer class does not accept an empty constructor. The working code should be:

Vector<Integer> integers = new Vector<Integer>();
integers.add(new Integer(2));

However, Java has the Auto boxing/unboxing concept. So the more concise code will be:

Vector<Integer> integers = new Vector<Integer>();
integers.add(2);

Vector's methods are synchronized so it supports multiple threading. However, it is not good in most situations. So I recommend you switch to ArrayList. So the updated version is:

ArrayList<Integer> integers = new ArrayList<Integer>();
integers.add(2);

And the final point, you should prefer using `List as the datatype because of Program to interfaces, not implementations List vs ArrayList. So the final version should be:

List<Integer> integers = new ArrayList<Integer>();
integers.add(2);
hqt
  • 29,632
  • 51
  • 171
  • 250
3

Integer doesn't have a no-arguments constructor.

The only constructors are the ones that take a String or an int respectively.

So you can do:

integers.add(new Integer("6"));

or

integers.add(new Integer(5));

The later one is deprecated though and should be replaced with Integer.valueOf(5).

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
1

You should have written Integer and pass it a parameter as follows:

Vector<Integer> intergers = new Vector<Integer>();
intergers.add(new Integer(1));
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
1

Integer does not have a no-arg constructor. Even the one-arg constructor is deprecated and you should avoid using that. You should use Integer.valueOf(int) instead e.g.

Integer x = Integer.valueOf(0);

However, you can simply do as follows:

Vector<Integer> intergers = new Vector<Integer>();
intergers.add(0);

and Autoboxing and Unboxing feature of Java will make sure that 0 is converted to Integer.valueOf(0) automatically.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110