Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace HashMap<String, Integer> with an array?

I have a program that count occurrences of words in given array. It keeps words and its quantity. For example, in given array:

String array[] = {"cat", "dog", "cat"}; 

I have 2 cats, and 1 dog. Making it with HashMap is quite simple:

HashMap<String, Integer> map = new HashMap<>();
for (int i = 0; i < wordarray.length; i++) {
    String word = wordarray[i].toLowerCase();
    if (map.containsKey(word)) {
        map.put(word, map.get(word) + 1);
    } else {
        map.put(word, 1);
    }
}

Then I just need to print it out:

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " : " + entry.getValue());
}

But is there any way to make it without HashMap only using arrays of objects?

like image 205
mazix Avatar asked Dec 08 '25 23:12

mazix


1 Answers

Create a custom class to hold your string and int values, and then use an array to hold them. In pseudo-code:

class Myclass
 public int myInt;
 public string MyString;
 //Constructor omited..


//Somewhere else..
MyClass[] my = new Myclass[2];
my[0] = new MyClass("string", 1);
like image 180
Oscar Avatar answered Dec 10 '25 11:12

Oscar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!