0

I am trying to learn ArrayList and Vector. If for example I have private Vector cardsInMyHand; can I change it to ArrayList. As you see or I am wrong.

    private Vector numbers;
    .
    .
    .
    Vector studentNumbers;
    studentNumbers = new Vector();
    public int getNumbers(Vector studentNumbers, int x)
    {

       if (x >= 0 && x < studentNumber.size())
       {
          return ((Integer)hand.elementAt(x)).intValue();
       } else
         {
            return 0;
         }
   }

change to private ??????; ...... ArrayList<String> studentNumbers = new ArrayList<String>(); Can I do this ?

   public int getNumbers(ArrayList studentNumbers, int x)
   {

     if (x >= 0 && x < studentNumber.size())
     {
        return ((Integer)hand.elementAt(x)).intValue();
     } else
       {
        return 0;
       }
   }
1
  • Vector is a Collection so you can just do numbers.toArray(new String[numbers.size()]) to convert the Vector<String> to a String[] Commented Nov 5, 2014 at 4:13

3 Answers 3

3

Yes, but your syntax has a few typos. And you should not use Raw Types. Finally, I suggest you use the List interface and read about Autoboxing and Unboxing.

public int getNumbers(List<Integer> studentNumbers, int x) {
    if (x >= 0 && x < studentNumbers.size()) {
        return studentNumbers.get(x);
    } else {
        return 0;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I don't understand about raw typesBox<String> stringBox = new Box<>(); Box rawBox = stringBox;
you mean this is a raw type ArrayList<String> studentNumbers = new ArrayList<String>();
@JayLo When you say just ArrayList objs; it is a raw type (it behaves like ArrayList<Object> objs;). The diamond operator on the right is short-hand, List<String> strings = new ArrayList<>(); for List<String> strings = new ArrayList<String>();.
2

Check the below example with type safety.

public ArrayList<String> convertVectorToList(Vector<String> studentNoVec){
		   return new ArrayList<String>(studentNoVec); 
		}
	
	public static void main(String[] args) {
		Vector<String> v= new Vector<String>();
		v.add("No1");
		v.add("No2");
		Test a = new Test();
		for(String no : a.convertVectorToList(v)){
			System.out.println(no);
		}
	}

Comments

0

First, Java Vector class considered obsolete or deprecated. If you want to convert Vector to an ArrayList use the below mentioned way. Simple and easy.

// convert vector to araryList  
public ArrayList convertVectorToList(Vector studentNoVec){
   return new ArrayList(studentNoVec); 
}

2 Comments

Please do not use Raw Types.
Yes! Its an example. Any Type can be used for Vector and ArrayList.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.