【问题标题】:Modifying an individual element in an array inside of an ArrayList修改 ArrayList 内的数组中的单个元素
【发布时间】:2019-05-06 18:49:58
【问题描述】:

我必须为一个类编写一段代码,该类计算输入文件中字符的出现次数,然后对其进行排序,我选择通过创建一个 ArrayList 来做到这一点,其中每个 object[] 有两个元素,字符和出现次数。

我试图增加表示出现次数的整数,但我无法让它工作

我目前的尝试是这样的:

  for(int i=0;i<=text.length();i++) {
        if(freqlist.contains(text.charAt(i))) {
            freqlist.indexOf(text.charAt(i))[1]=freqlist.get(freqlist.indexOf(text.charAt(i)))[1]+1;
        }

    }

文本只是一个包含所有输入文件的字符串

freqlist 之前声明为

List<Object[]> freqlist=new ArrayList<Object[]>();

所以,我想知道如何增加或修改数组列表中的数组元素

【问题讨论】:

  • 看起来您正在尝试将列表元素同时视为字符和 Object[2] 数组。
  • 您应该尝试使用键是字符,值是出现次数的映射。您可以使用 merge 方法来更新计数。
  • 使用Map&lt;Character, Integer&gt; 可能更容易跟踪计数。排序部分不清楚。或者使用分组流text

标签: java arrays arraylist


【解决方案1】:

一般来说,您的程序中有 3 个错误会阻止它运行。它不能工作,因为for循环有i&lt;=text.length(),它应该是i &lt; text.length(),否则你会有异常。第二个错误是你使用freqlist.contains(...),你假设对象数组的两个元素是相同的,或者换句话说数组是相等的,这是错误的假设。第三个错误是使用 freqlist.indexOf(...) 再次依赖于数组相等。尽管此数据结构 List&lt;Object[]&gt; 对于该任务而言效率低下,但我还是使示例正常工作。最好使用Map&lt;Character,Integer&gt;。 这里是:

import java.util.ArrayList;
import java.util.List;

class Scratch {
    public static void main(String[] args) {
        String text = "abcdacd";

        List<Object[]> freqlist= new ArrayList<>();

        for(int i=0;i < text.length();i++) {
            Object [] objects = find(freqlist, text.charAt(i));
            if(objects != null) {
                objects[1] = (Integer)objects[1] +1;
            } else {
                freqlist.add(new Object[]{text.charAt(i), 1});
            }

        }

        for (Object[] objects : freqlist) {
            System.out.println(String.format(" %s  =>  %d", objects[0], objects[1]));
        }
    }

    private static Object[] find(List<Object[]> freqlist, Character charAt) {
        for (Object[] objects : freqlist) {
            if (charAt.equals(objects[0])) {
                return objects;
            }
        }
        return null;
    }
}

【讨论】:

    【解决方案2】:

    我这样做的方法是首先解析文件并将其转换为字符数组。然后将其发送到 charCounter() 方法,该方法将计算一个字母在文件中出现的次数。

    /**
         * Calculate the number of times a character is present in a character array
         *
         * @param myChars An array of characters from an input file, this should be parsed and formatted properly
         *                before sending to method
         * @return A hashmap of all characters with their number of occurrences; if a
         *                letter is not in myChars it is not added to the HashMap
         */
        public HashMap<Character, Integer> charCounter(char[] myChars) {
            HashMap<Character, Integer> myCharCount = new HashMap<>();
            if (myChars.length == 0) System.exit(1);
            for (char c : myChars) {
                if (myCharCount.containsKey(c)) {
                    //get the current number for the letter
                    int currentNum = myCharCount.get(c);
    
                    //Place the new number plus one to the HashMap
                    myCharCount.put(c, (currentNum + 1));
                } else {
                    //Place the character in the HashMap with 1 occurrence
                    myCharCount.put(c, 1);
                }
            }
            return myCharCount;
        }
    

    【讨论】:

      【解决方案3】:

      如果您使用 Java 8 进行分组,您可以使用一些 Stream 魔法:

      Map<String, Long> map = dummyString.chars() // Turn the String to an IntStream
              .boxed() // Turn int to Integer to use Collectors.groupingBy
              .collect(Collectors.groupingBy(
                      Character::toString,     // Use the character as a key for the map
                      Collectors.counting())); // Count the occurrences
      

      现在您可以对结果进行排序了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-11
        相关资源
        最近更新 更多