简体   繁体   中英

java generics compile error, generic class on the stack

I'm not sure why this doesn't work in Java:

import java.util.Map;

public class FreqCounter<T,R> {
    private Map<T, Integer> hist;
    private R item;
    public FreqCounter (final R item_) {
        item = item_;
    }
    public T getMostFrequentElement() {
        T most_frequent_element = T();
        Integer highestcount = 0;
        for(T t : item) {
            Integer count = hist.get(t);
            if(count == null) {
                hist.put(t, 1);
            }
            else {
                hist.put(t, count + 1);
            }
            if(count + 1 > highestcount) {
                most_frequent_element = t;
                highestcount = count + 1;
            }
        }
        return most_frequent_element;
    }
}


class HelloWorld {
    public static void main(String[] args) {
        String s = "aaabbcccc";
        FreqCounter<Character, Integer> counter = new FreqCounter<Character, Integer>(s);
    }
}

Problem lines:

 1. T most_frequent_element = T();
 2. for(T t : item)
 3. FreqCounter<Character, Integer> counter = new FreqCounter<Character, Integer>(s);
  1. Cannot find symbol: method T()
  2. required: array or java.lang.Iterable, found: R
  3. Required java.lang.Integer Found: java.lang.String reason: actual argument java.lang.String cannot be converted to java.lang.Integer by method invocation conversion

What I was trying to do was make a class that could count how many times an element in an iterable container shows up. Originally I just wanted to make it to count characters in a string but I thought I could make it more general. I think some of this would work in C++?

Also, does FreqCounter<Character, Integer> counter = new FreqCounter<Character, Integer>(s) ; need to be "newed" as opposed to declared on the stack?

T is a Generic type, not a real one, and one of the limitations of generics is that you cannot instantiate a new one (which is what I think you were trying to do here).

What you can do though is assign, call methods in, keep references too, duplicate references too, etc.

What you probably actually wanted to do was pull the set of T s out of the keySet of the Map .

T t = null;
int count = 0;
for (Entry<T, Integer> e: hist.entrySet()) {
   if (e.getValue() > count) {
      count = e.getValue();
      t = e.getKey();
   }
}
return t;

Java Generics provide a lot of the same functionality that C++ templates do, but they work in quite a different way. Quite apart from anything else you only have one ArrayList class no matter how many different ways you instantiate one. The generics are used for compiler time type checking and then erased and are not present at all during run time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM