我编写了以下简短的程序,提示用户构造一个整数 ArrayList,然后显示删除了重复项的同一数组。该程序可以很好地处理简单的数字,例如 1、10 甚至 100。请注意,排序不是该程序中的问题,因为我只是为自己编写的。不过,我确实理解不对程序进行排序的含义。
稍大的数字不会被正确检测为重复项。例如,如果我选择构造一个包含 2 个整数的数组,两者的值均为 700,则该方法不会删除重复项。是否还有其他一些我不理解的概念,或者我的代码中是否有一个我忽略的小错误?
import java.util.*;
public class DuplicateArray
{
public static void main( String [] args )
{
// Variables
Scanner scan = new Scanner(System.in);
// Prompt user and create an array
System.out.print("\nHow many items will your array contain: ");
int size = scan.nextInt();
ArrayList<Integer> numbers = new ArrayList<Integer>(size);
// Construct the array
for( int i = 0; i < size; i++ )
{
System.out.print("Item #" + (i+1) + ": ");
numbers.add( scan.nextInt() );
}
// Remove duplicates
compress( numbers );
// Print compressed array
System.out.println("\nBelow is that same array with duplicates removed.");
for( int i = 0; i <= numbers.size()-1; i++ )
{
System.out.print( numbers.get(i) + " " );
}
}
/*
* Removes duplicates from the input array
*/
public static void compress( ArrayList<Integer> numbers )
{
// If the array is of size 1, then there are no duplicates to check for */
if( numbers.size() <= 1 )
{
return;
}
// Traverse the array backwards */
for( int i = numbers.size() - 1; i > 0; i-- )
{
if( numbers.get(i) == numbers.get(i-1) )
{
numbers.remove(i);
}
}
}
}
最佳答案
用于比较的不是这个
numbers.get(i) ==numbers.get(i-1)
但是 numbers.get(i).equals(numbers.get(i-1))
方法.
这种奇怪行为的原因是 JVM 内部有一个从 -128..127 开始的 Integer
值的缓存(请参阅 Integer#valueOf
方法实现)。因此 numbers.get(i) ==numbers.get(i-1)
仅适用于此数字范围。但对于不在该范围内的数字,这种比较操作不起作用,您必须使用 equals
方法。
关于java - 从数组中删除重复条目的程序不会删除某些条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39693300/