简体   繁体   English

字符串比较Java

[英]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 例如2D阵列

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. 通过Arrays.asList(T ... a)将每个组合封装为一个列表,以保持其顺序并将其存储在HashSet中,以确保contains(Object o)的唯一性和恒定时间性能,以确定是否已经存在。

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 不确定计划使用哪种语言,但是可以检查两个字符串在C#中的值是否相同,如下所示

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. 它与其他语言(例如java,vb.net)非常相似。

EDIT: the java tag was added after I started writing my answer.. sorry 编辑:我开始编写答案后添加了Java标记。

Hope this helps, 希望这可以帮助,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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