我正在学习数组,我做了一些安静的实验,大部分都进行得很顺利,但现在我被困住了。 我想要存档的是,查找特定值(String、int 或其他)是否存在于数组中,如果存在,则将该值用于某些东西,即下面的代码,我基本上计算该值在数组中出现了多少次数组:
package arraysOnly;
import java.util.*;
public class ArrayContainsString
{
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
int arraySize = 0;
int wordCount = 0;
System.out.println("How many words are you gonna type?: ");
arraySize = sc.nextInt();
String[] words = new String[arraySize]; // Simple array, the size of which will be decided from the user-input
for(int count = 0; count < arraySize; count++)
{
System.out.println("Enter your " + (count+1) + ": ");
words[count] = sc.next();
}
//Basically this is the part I'm having troubles
if(in_array("ubt", $words)
{
wordCount++;
}
}
}
这件事我知道,
if(Arrays.asList(words).contains("ubt"));
它基本上将数组转换为 List/ArrayList 或其他任何东西,但是我只想在可能的情况下将其视为数组。
最佳答案
数组是错误的数据结构; Set
是选择的武器:
Set<String> words = new HashSet<>()
for (int count = 0; count < arraySize; count++) {
System.out.println("Enter your " + (count+1) + ": ");
words.add(sc.next());
}
if (words.contains("ubt"))
wordCount++;
}
无论集合有多大,HashSet
的contains()
方法都会在常数时间内完成。虽然性能与这种用法的小输入大小无关,但养成为工作选择正确工具的习惯是很好的。它还使您的代码更清晰。
一般来说,除非万不得已,否则不要使用数组;它们很少用于商业代码。
关于java - 在数组(不是列表)中查找特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32102336/