Java - constructing multiple objects of a generic class in a static function -


i'm trying implement generic class defines order on objects. here's snippet of code:

import java.util.arraylist;  public class orderedobject<t> implements comparable<orderedobject<t>> {      private t object;     private int orderid;      public orderedobject(t object, int orderid) {         this.object = object;         this.orderid = orderid;     }      public t getobject() {         return object;     }      public static arraylist<orderedobject<t>> defineorder(arraylist<t> objects) {         arraylist<orderedobject<t>> orderedobjects = new arraylist<orderedobject<t>>();         (int = 0; < objects.size(); i++) {             t object = objects.get(i);             orderedobject<t> orderedobject = new orderedobject<t>(object, i);             orderedobjects.add(orderedobject);         }         return orderedobjects;     }      @override     public int compareto(orderedobject<t> o) {         return orderid - o.orderid;     }  } 

in defineorder() i'm trying initialize multiple objects of class @ once - want order defined positions of generic objects in array, , static function take generic object t array, , return orderedobject<t> array. unfortunately, code wrote won't compile, says reference static field t cannot made, because t not static.

why t not static? also, there way out of situation?

the type parameter t defined on class in scope in non-static contexts. it's not in scope inside static methods.

however, can declare type parameter static method itself. note t not same class's t. renamed without affecting anything, long references t inside static method renamed accordingly.

public static <t> arraylist<orderedobject<t>> defineorder(arraylist<t> objects) { 

section 8.1.2 of jls states:

it compile-time error refer type parameter of generic class c in of following:

  • the declaration of static member of c (§8.3.1.1, §8.4.3.2, §8.5.1).

  • the declaration of static member of type declaration nested within c.

  • a static initializer of c (§8.7), or

  • a static initializer of class declaration nested within c.

(emphasis mine)


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -