java - 在数组(不是列表)中查找特定值

标签 java arrays

我正在学习数组,我做了一些安静的实验,大部分都进​​行得很顺利,但现在我被困住了。 我想要存档的是,查找特定值(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++;
}

无论集合有多大,HashSetcontains() 方法都会在常数时间内完成。虽然性能与这种用法的小输入大小无关,但养成为工作选择正确工具的习惯是很好的。它还使您的代码更清晰。

一般来说,除非万不得已,否则不要使用数组;它们很少用于商业代码。

关于java - 在数组(不是列表)中查找特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32102336/

相关文章:

arrays - 在 C 中从 stdin 获取数字到数组

ios - Swift/Xcode 纯值类型数组泄漏

java - 这是资源泄漏还是误报?

java - 无法使用 GSON lib 反序列化对象

java - android - 对于在许多 Activity 中重复的一些java代码使用什么方法

java - 如何创建字符串的所有元音组合并将每个组合添加到 ArrayList

java - 如何从结果集中获取日期

c++ - 负数组索引

javascript - netsuite suitescript 2.0版如何设置多选字段的值?

javascript - 我无法理解这段代码是如何工作的