Re: Matching Items in a vector
nemadrias schrieb:
Hi -
I was using two arrays to go through two lists of numbers in the same
format, such as below:
The numbers are always 15 numbers followed by some text. I ONLY care
about the first 15 numbers, not the text.
100121242110124ABC 000121241000124ABC
000121236300124ABC 000121236300124ABC
005151533414124ABC 001121231009909ABC
000124576700188ABC 123516800785656ABC
I had passed both sets of numbers into two separate arrays, and was
able to use the regionMatches method to compare the first 15 numbers to
find duplicates. I want to be able to remove any duplicates from the
first array so I can return only the unique numbers from the first list
(left side). Unfortunately, arrays don't have a "removeAtIndex" method
while Vectors DO have the ability to remove from the vector array. So
I tried vectors...But, Vectors can't use the method regionMatches which
allows me to check those first 15 numbers...
I consider that there are at least two entries where the three letters
at the end differ.
If you put Strings into a Collection (Vector implements this interface),
you can use String#regionMatches on it's elements, of course.
If you use Java >= 1.5 you can use generics to make the Vector type-safe:
Vector<String> myVector = new Vector<String>();
Then you can use regionMatches without a cast:
if ( myVector.get(i).regionMatches(...
If you don't use Java >= 1.5 you have to cast:
if ( ((String)myVector.get(i)).regionMatches(...
BTW: if you don't access myVector in more than one thread, you should
use ArrayList instead of Vector since Vector is synchronized.
Second: you could have used a custom class to represent your entries.
class Entry {
private String content;
public Entry( String content ) {
if ( content == null )
throw new IllegalArgumentException(
"Cannot have null content.");
if ( content.length() < 15 )
throw new IllegalArgumentException(
"Content too short" );
this.content = content;
}
public String toString() {
return content;
}
public boolean equals( Object o ) {
if ( o == null || !(o instanceof Entry) )
return false;
return (content.regionMatches(0, o.toString(), 0, 15));
}
public int hashCode() {
return content.substring(0, 15).hashCode();
}
}
With this class, you can manage your entries in the form of collections
(Java 1.5 syntax):
HashSet<Entry> firstSet = new HashSet<Entry>();
HashSet<Entry> secondSet = new HashSet<Entry>();
// fill the sets, e. g. at loading time or if you only have
// vectors:
// for ( String s : myVector )
// firstSet.add( new Entry(s) );
// for ( String s : myVector2 )
// secondSet.add( new Entry(s) );
// now, remove the duplicates:
firstSet.removeAll(secondSet);
Of course, this works with any Collection not just sets.
Third: ... there are many ways...
Bye
Michael