karse23
karse23

Reputation: 4115

How to do something similar to an include in C?

Forgive my ignorance, but I am a beginner in java that comes from using structured programming and I don't know how I can do something similar to include in c, php or other similar languages.

I have a main class that contains a quite big array. I would like know how to separate the array putting it into another file or class and make something like an include in the main class to use this array

I want the array initialized in the file or external class and then from the main class just call the resort.

How I can do this? Can anyone post an example?

Thanks!

Upvotes: 2

Views: 259

Answers (7)

user177800
user177800

Reputation:

Java does not have a pre-processor and does not have the equivalent of include semantics of C or C++. include just inserts the contents of another file in the place of the include statement, in Java import just tells the compiler to include the namespace of imported classes for resolution of the referenced classes.

To do what you want in the most Java like manner you would want to put your data in a file that is on the classpath and then read that file in at run time using a BufferedReader to read one line of data at a time and build a type safe List<String> most likely an ArrayList<String>. Put your information for the List in a file called datafile.txt in the same directory as the Main.class and this will work.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Main
{
    public static void main(final String[] args)
    {
        try
        {
            final InputStream inputStream = Main.class.getResourceAsStream("datafile.txt");
            final InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            final BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            final List<String> list = new ArrayList<String>();
            while (bufferedReader.ready())
            {
                list.add(bufferedReader.readLine());
            }

            int index = 0;
            for (final String s : list)
            {
                System.out.format("%d:%s\n", index, s);
                index++;
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}

Upvotes: 1

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 37960

As you probably know, in C, the #include <file.h> directive simply pastes the entire content of file.h into the current source file. file.h typically only contains declarations of functions that are defined in file.c (or in other files with unrelated names), as well as struct declarations and #defines. The compiler then compiles the current source file without knowledge of the actual implementation of the functions that are declared in the header files. After compilation, the linker locates the actual implementation in the other compiled files and connects your compiled file to it.

In Java, the compiler itself is able to look for definitions in other files; hence, there is no need for header files. Instead, each file declares itself to be a part of a package, and each file typically contains one class (and all methods (same as functions in C) must reside inside classes). In the top of each file, one can simply list the package qualified name all classes that one wishes to refer to, with the import statement. A complete example:

MainClass.java:

import foobar.OtherClass;

public class MainClass {
    public static void main(String[] args) {
        System.out.println(OtherClass.SomeArray.length);
    }
}

OtherClass.java:

package foobar;

public class OtherClass {
    public static final int[] SomeArray = {3, 42, 0, 9};
}

Upvotes: 2

OscarRyz
OscarRyz

Reputation: 199264

Try using import

//File1.java 
package some;
class SomeClass { 
   public static int [] bigarray =  initFromFile();

   private static int[] initFromFile() { 
    ...
   }
}
//File2.java
package other;

import some.SomeClass; //<-- use SomeClass

class Other {
   public static void main( String ... args ) { 
      // use it
      int [] data = SomeClass.getData(); //<-- get the array
    }
}

You should consider not using class level attributes ( those with static ) and a better data structure ( like List ).

But for what you asked, this is the answer.

Upvotes: 1

Arve
Arve

Reputation: 8128

import java.util.ArrayList;
public class ImportInJava {
    public static void main(String[] args) {
        ArrayList<String> theArrayList = ArrayListCreator.getArrayList();
        System.out.println(theArrayList);
    }
}

and in another class:

import java.util.ArrayList;

public class ArrayListCreator {
    public static ArrayList<String> getArrayList() {
        ArrayList<String> list = new ArrayList<String>();
        list.add("Some");
        list.add("Values");
        return list;
    }
}

Upvotes: 1

GreenMatt
GreenMatt

Reputation: 18590

The closest Java has to C's include is the import statement, if it's applicable to your situation. Try the Sun - er Oracle Java Tutorial about packages for more about using it.

That said, you you might want to try using Java's ArrayList instead of rolling your own array class.

Upvotes: 0

Fortyrunner
Fortyrunner

Reputation: 12782

Slightly off topic but...

If you wish to write idiomatic Java, learn the Collections API as soon as possible.

They are generally much more useful than arrays.

E.g. You can use a TreeMap or a TreeSet to automatically sort a collection of data as you create it.

Upvotes: 0

Alain Pannetier
Alain Pannetier

Reputation: 9514

You can define your array as a public static final array in its own class and access it from any other class.

public class MyArray {
    public final static String [] myArray = { "one", "two", "three" } ;
}



public class MyMain {
    public static void main(String[] args) {
        for (String s : MyArray.myArray ) {
            System.out.println( s );
        }
    }
}

Upvotes: 3

Related Questions