Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/neo4j/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
试图在Java中的ArrayList实现中找到唯一的元素。getUnique方法 公共类MyArrayList实现MyList{ int num;//列表中的项目数 T[]vals;//用于存储内容 @抑制警告(“未选中”) 公共MyArrayList(){ num=0; VAL=(T[])新对象[3]; } 公共T getUnique(){ T=null; 整数计数=0; 对于(int i=0;i_Java_Arrays_Arraylist - Fatal编程技术网

试图在Java中的ArrayList实现中找到唯一的元素。getUnique方法 公共类MyArrayList实现MyList{ int num;//列表中的项目数 T[]vals;//用于存储内容 @抑制警告(“未选中”) 公共MyArrayList(){ num=0; VAL=(T[])新对象[3]; } 公共T getUnique(){ T=null; 整数计数=0; 对于(int i=0;i

试图在Java中的ArrayList实现中找到唯一的元素。getUnique方法 公共类MyArrayList实现MyList{ int num;//列表中的项目数 T[]vals;//用于存储内容 @抑制警告(“未选中”) 公共MyArrayList(){ num=0; VAL=(T[])新对象[3]; } 公共T getUnique(){ T=null; 整数计数=0; 对于(int i=0;i,java,arrays,arraylist,Java,Arrays,Arraylist,,我已在代码中添加了一些修复程序: public class MyArrayList<T> implements MyList<T>{ int num; //number of things in the list T[] vals; //to store the contents @SuppressWarnings("unchecked") public MyArrayList() { num

,我已在代码中添加了一些修复程序:

public class MyArrayList<T> implements MyList<T>{
    int num;        //number of things in the list
    T[] vals;       //to store the contents

    @SuppressWarnings("unchecked")
    public MyArrayList() {
        num = 0;
        vals = (T[]) new Object[3];
    }

public T getUnique(){
        T distinct = null;
        int count = 0;
        for (int i=0; i<vals.length; i++){
            distinct =  vals[i];
            for (int j = 0; j<vals.length; j++){
                if (vals[j] == vals[i]){
                    count++;
                }
                if (count == 1){
                    return distinct;
                }
            }
        }
        if (distinct == null){
            throw new IllegalArgumentException();
        }
        return distinct;
    }
public T getUnique(){
T=null;
int count=0;//修复:将此初始化移到i循环中

对于(int i=0;iPatrick Parker的建议将修复您的代码,但我想为在列表中查找唯一元素的问题提供一个更干净、更快的解决方案。此算法在时间
O(n)
中运行,而不是
O(n^2)

此代码使用Java 8流和
可选
。下面是同一算法的另一个实现,它不使用Java 8语言功能;如果您从未遇到过流,您可能会发现它更容易理解

Integer[] vals = {1,2,3,1,2,4};
System.out.println(getUnique(Arrays.asList(vals))
        .orElseThrow(NoSuchElementException::new));
private static T getUnique(列表arr){
Map numOccurrences=newhashmap();
对于(T项:arr){
numOccurrences.put(项,1+numOccurrences.getOrDefault(项,0));
}
对于(T项:arr){
if(numOccurrences.get(item)==1){
退货项目;
}
}
抛出新的NoTouchElementException();
}

如果方法getUnique不带参数,你如何传递列表?你在方法内部初始化它?确切的问题是什么?@mirzak看起来像是他的列表实现方法。Ram:两个问题:这是家庭作业吗?你的问题是什么?啊,是的,你是对的。我现在明白了。@mirzak我在JUnit测试中初始化列表e、 很好。非常感谢。@RamSharma是有人回答您的问题时要做的事情。若要将答案标记为已接受,请单击答案旁边的复选标记,将其从灰色变为已填写。无需对您的问题或答案添加评论即可说“谢谢”。
public static <T> Optional<T> getUnique(List<T> ls) {
    // Create a map whose keys are elements of the list and whose values are
    // lists of their occurences. E.g. [1,2,3,1,2,4] becomes {1->[1, 1],
    // 2->[2, 2], 3->[3], 4->[4]}. Then elements.get(x).size() tells us how
    // many times x occured in ls.
    Map<T, List<T>> elements = ls.stream()
            .collect(Collectors.groupingBy(x -> x));
    // Find the first element that occurs exactly one time in ls.
    return ls.stream().filter(x -> elements.get(x).size() == 1)
            .findFirst();
}
Integer[] vals = {1,2,3,1,2,4};
System.out.println(getUnique(Arrays.asList(vals))
        .orElseThrow(NoSuchElementException::new));
private static <T> T getUnique(List<T> arr) {
    Map<T, Integer> numOccurrences = new HashMap<>();
    for (T item : arr) {
        numOccurrences.put(item, 1 + numOccurrences.getOrDefault(item, 0));
    }

    for (T item : arr) {
        if (numOccurrences.get(item) == 1) {
            return item;
        }
    }

    throw new NoSuchElementException();
}