Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Java Cheatsheet

Although I had programmed in Java when studying at university, it turns out I hadn't really used the language much since starting this blog. Hence when I had an itch to get back into it this weekend, I struggled just to remember the basics so I started this cheatsheet.

Arrays / Collections

Create Array Of Integers

int[] nonTraversableTileIDs = {2,4};

Create A List

Lists are generic collections where you specify the type of objects they contain. Since they contain objects, not primitives, you may have to use the object type of a primitive. E.g. here is how you would create a list of integers by using the Integer object.

List<Integer> myList = new ArrayList<>();
myList.add(1);
myList.add(2);
myList.add(3);

// Alternatively...
List<Integer> myList = new ArrayList<>(Arrays.asList(1, 2, 3));

Check Array Contains Element

return ArrayUtils.contains(myArray, myElement);

Loop Over List

for (MyObjectType element : myList) 
{
    element.doSomething();
}

Randomly Pick Element From Array

Random randomGenerator = new Random();
int index = randomGenerator.nextInt(myList.length);
MyElement element = myArray[index]

Filesystem

Get Array Of Files In Folder

File folder = new File("path/to/my/folder");
File[] filesArray = folder.listFiles();

for (int i = 0; i < listOfMusicFiles.length; i++) 
{
    if (filesArray[i].isFile()) 
    {
        System.out.println("File " + filesArray[i].getName());
    } 
}

References

Last updated: 16th August 2018
First published: 16th August 2018