-
vector add
I am trying to add an object to the vector, the object consists of 2 elements, str1 and str2. i want the vector to add the object only if str1 doesn't repeat itself, in other words no duplicates of str1. str2 can have the same element.
please help
Code:
public class main {
public static void main(String[] args) {
A a = new A();
B b = new B("AA","GGG");
a.addToVector(b);
b = new B("BB","LLL");
a.addToVector(b);
b = new B("AA","PPP");
a.addToVector(b);
b = new B("DD","LLL");
a.addToVector(b);
System.out.println(a);
}
}
Code:
public class B {
private String str1;
private String str2;
public B(String str1, String str2){
this.str1 = str1;
this.str2 = str2;
}
public String getStr1(){
return this.str1;
}
public String getStr2(){
return this.str2;
}
public String toString(){
return str1+" "+str2;
}
}
Code:
public class A {
Vector vec = new Vector();
public void addToVector(Object obj){
for(Iterator iter = vec.iterator(); iter.hasNext();){
Object o = iter.next();
if(o.equals(obj)){
break;
}
}
vec.add(obj);
}
public String toString(){
return vec.toString();
}
}
-
Re: vector add
Are you using Vector class for any particular reason? And in this situation in the method addToVector, you want to cast your 'Object' to 'B' (you should be using Generics btw) and check if the first String in B matches the first String in 'obj' (Which should also be 'B' and not 'Object')
Also look at: http://docs.oracle.com/javase/6/docs...l/HashMap.html
-
Re: vector add
Moved from Advanced Java
db