不允许重复的数组(Java)

knpiaxh1  于 2022-12-25  发布在  Java
关注(0)|答案(6)|浏览(237)

我确信这个问题有一个简单的答案,因为我认为我以前用过或听说过它,但似乎找不到它,可能是因为谷歌不懂英语。基本上我需要类似或相同的东西,不允许重复值的数组(在Java中)。
示例:整数[]示例= {1,2,2,3,4,4}
应该是{1,2,3,4}
希望这一点足够清楚,即使谷歌不能理解,人类也能理解。

gev0vcfq

gev0vcfq1#

你应该使用一个Set实现,而且Java中的数组不能像一个集合那样工作,但是使用一个像HashSet这样的Set实现,就可以管理集合中元素的唯一性。

nhaq1z21

nhaq1z212#

你可以使用HashSet。对于整数,它会很好地工作。但是如果以后你打算存储Objects,你应该重写hashCode()equals()方法。因为HashSet内部使用equals()hashcode()来检查是否相等。
Read More about hashcode and equals here

js81xvg6

js81xvg63#

尝试使用Set实现
例如:

public static void main(String[] args) {
    Set<Integer> numbers = new HashSet<>();

    numbers.add(3);
    numbers.add(5);
    numbers.add(5);
    numbers.add(5);
    numbers.add(6);
    numbers.add(12);

    System.out.println(numbers);   
}

将产生:

[3, 5, 6, 12]
c8ib6hqw

c8ib6hqw4#

import java.util.HashSet;
 import java.util.Set;
 public static void main(String[] args) {
 Set<Integer> numbers = new HashSet<Integer>();

 numbers.add(3);
 numbers.add(5);
 numbers.add(5);
 numbers.add(5);
 numbers.add(6);
 numbers.add(12);

 System.out.println(numbers);   
 }
 Take this.you can get what you want to get.
6tdlim6h

6tdlim6h5#

尝试使用Hashset删除重复项的代码

public static Integer[] removeDuplicateUsingSet(Integer[] example) {
    List<Integer> inputList = Arrays.asList(example);
    Set<Integer> inputSet = new HashSet<Integer>(inputList);
    Integer[] ints = new Integer[inputSet.size()];
    int index = 0;
    for (Integer i : inputSet) {
        ints[index++] = i;
    }
    return ints;
}

public static void main(String[] args) {

    Integer[] example = { 1, 2, 2, 3, 4, 4 };
    example = removeDuplicateUsingSet(example);
    for(int i = 0 ;i < example.length;i++){
        System.out.println(example[i]);
    }
}
epggiuax

epggiuax6#

如果在添加元素时可以使用散列集,则不允许重复值,否则可以像这样使用:

import java.util.ArrayList;
 import java.util.Arrays;
 public class NotDuplicateArray {

        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Integer[] Value={1,2,2,3,3,4,5,6,6};
            ArrayList<Integer> Check=new ArrayList<Integer>();
            int count=0;
            int x = 1;

            for(int i=0;i<Value.length;i++){
                if(Check!=null){
                    if(!Check.contains(Value[i])){
                        Check.add(Value[i]);
                    }

                }else{
                    Check.add(Value[i]);
                }

            }
            for(int v:Check){
                System.out.println(v);
            }

        }
    }

相关问题