简体   繁体   中英

String Comparison Java

I have a collection of lock combinations that is being outputed. I want to make sure that no combination is repeated. The combinations are not just ints. I converted them all to Strings for simplicity of the format. What is the line of code that allows me to loop and compare each string so that none are repeated? Any ideas? eg 2D arrays

Thank you.

It might be easier to store your lock combinations in a set. This would make it much easier to ensure that they are unique.

This will be much faster too, since you do not need to compare every string with all of the other strings in your dataset...

Encapsulate each combination as a List via Arrays.asList(T... a) to keep their ordering and store those in a HashSet to ensure uniqueness and constant time performance on contains(Object o) to determine if it's already present.

import java.util.Arrays;
import java.util.List;
import java.util.HashSet;

public class UniqueLocks {
    public static void main (String[] args) {
        List lock1 = Arrays.asList("1", "22", "333");
        List lock2 = Arrays.asList("a", "bb", "ccc");
        List lock3 = Arrays.asList("eee", "bbb", "ccc");

        HashSet uniqueLocks = new HashSet(Arrays.asList(lock1, lock2, lock3));

        List duplicateLock = Arrays.asList("1", "22", "333");

        if (uniqueLocks.contains(duplicateLock)) {
            System.out.println("Lock [" + duplicateLock + "] already present.");
        }
    }
}

Not sure what language your planning to do this with but you can check to see if two strings have the same value in C# like so

String myString = "Hello World!"; 
String myString2 = "Hello World!"; 

if(myString.equals(myString2)) {
    //do something cause we have a match

}

if you have an array of strings you can just loop through them.

its very similar in other languages like java, vb.net.

EDIT: the java tag was added after I started writing my answer.. sorry

Hope this helps,

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM