Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make a custom class that can have [] used on it in Java, similar to an array?

With Java, is there a way to make a custom class that can have the [] accessor used on it like an array?

Normal array

int[] foo = int[5];
foo[4] = 5;
print(foo[4]);
//Output: "5"

Custom Class

class Bar {
    //Custom class that uses index as a ref
}

Bar foo = new Bar(5);
foo.set(4, 5);
print(foo[4]);
//Output: "5"
like image 855
Eforen Avatar asked Dec 05 '12 16:12

Eforen


People also ask

Can you make an array of classes in Java?

Answer: Yes. Java can have an array of objects just like how it can have an array of primitive types.


1 Answers

No, you cannot overload [] operator for your classes in Java. But you can create getter for your array.

like image 156
bellum Avatar answered Nov 15 '22 16:11

bellum