Creating data structure in Java

23,402

Solution 1

You could use inner/nested classes. You'll have only one .java file, but nested classes will all have their own .class file when compiling.

Solution 2

You have to create a class if you want a data structure. Just to avoid creating multiple .java files, you can put those classes in a single .java file. Assuming, Test.java-

public class Test {

    class InnerOne {
    }

    void m() {
        class InnerMost {
        }
    }
}

class Dummy {
}

class OnMore {
}

Solution 3

You can create several small, auxiliary classes in one .java file, but they can not be public. So for example you can create a public class, whose name corresponds to a file and a couple of helper classes that are not public.

As for class per data structure in java, java has only one way of creating abstract data types - classes, if you're not satisfied with this - try using other JVM languages, like Scala, it is far more flexible in this regard.

Share:
23,402
turtlesoup
Author by

turtlesoup

Updated on December 11, 2020

Comments

  • turtlesoup
    turtlesoup over 3 years

    I'm wondering if there is a good way to create a new data structure in Java that avoids creating new class file. According to this post, the Java's equivalence to struct in C is simply a class. However I find it redundant to create a whole new file for a class that simply have a couple of public fields, ex: x,y coordinates of a point. In C, the data structure can be defined within the .c file that uses it, which is a lot more simple. Is this actually the only way in Java?