简体   繁体   中英

Generic Set/Array Initialization - Java

I am trying to fulfill this interface

Set<T> filter(UnaryRelation<T> x) 

I need to create a set containing elements in a set that satisfy x. I can't seem to figure out how to initialize the set being that it is said to be generic. How can I create it so it is not generic?

Set<T> filteredArray =  new Object<T>[size()];

You need to decide what T is when you invoke that code. For example:

class Test<T> {

    private Set<T> filter;

    public Test() {
        filter = new HashSet<T>();
    }

    public Set<T> getFilter() {
        return filter;
    }
}

class Main {
    public static void main(String[] args) {
        Test<Integer> test = new Test<Integer>();
        Set<Integer> filter = test.getFilter();
    }
}

https://docs.oracle.com/javase/tutorial/java/generics/types.html

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