PatternTest.java
DateAndTime.java
ReadStdin.java
ZipRead.java
Rounding.java
PQ.java
java2matlab.java
googlejsonTest.java
MD5.java
FileScan.java
ReflectionAllFields.java
PQMinMax.java
CustomSort.java
RunProcess.java
RegExpressions.java
enumValues.java
jsonIOTest.java
SimpleXMLTest.java
JDBCTest.java
HashMapTest.java
OutOfMemory.java
IterateAndRemoveFromCollection.java
ApacheCLIExample.java
FileReadWrite.java
TIntSetTest.java
TIntMapTest.java
Student.java
LinkedListTest.java

PatternTest.java

package tests;

import java.util.Scanner;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 06/06/13 10:37 AM
 */
public class PatternTest {
	public static void main(String[] args) {
		Scanner src = new Scanner(" 1 	2\t3 4		\t\t and now we have some\t text at the end!");
		src.useDelimiter(Pattern.compile("\\s*"));

		System.out.println(src.nextInt());
		System.out.println(src.nextInt());
		System.out.println(src.nextInt());
		System.out.println(src.nextInt());

		System.out.println(src.nextLine()); // reads everything and moves to the next line if such exists
	}
}
DateAndTime.java

package tests;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 09/11/12 12:56 PM
 */

public class DateAndTime {

	public static void main(String[] args) throws Exception {
		SimpleDateFormat format = new SimpleDateFormat("dd/MM/yy HH:mm:ss");

		Date d1 = new Date();
		Thread.currentThread().sleep(2000);
		Date d2 = new Date();

		long diff = d2.getTime() - d1.getTime();
		long diffSeconds = diff / 1000;
		long diffMinutes = diff / (60 * 1000);
		long diffHours = diff / (60 * 60 * 1000);
		System.out.println("Time in seconds: " + diffSeconds + " seconds.");
		System.out.println("Time in minutes: " + diffMinutes + " minutes.");
		System.out.println("Time in hours: " + diffHours + " hours.");

		System.out.println(format.format(d1));
		System.out.println(format.format(d2));
	}

}
ReadStdin.java

package tests;

import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 23/05/13 7:57 PM
 */
public class ReadStdin {

	public static void main(String args[]) {

		System.out.println("usage: program < file.txt\n or cat file.txt | program");

		Scanner sc = new Scanner(System.in);
		while(sc.hasNext()){
			System.out.println(sc.nextLine());
		}
	}
}
ZipRead.java

package tests;

public class ZipRead {
/*
 zipFile = new ZipFile(fileName);

 for (Enumeration e = zipFile.entries(); e.hasMoreElements();) {

 ZipEntry zipEntry = (ZipEntry) e.nextElement();

 BufferedReader zipReader = new BufferedReader(new InputStreamReader(zipFile.getInputStream(zipEntry)));
*/
}
Rounding.java

package tests;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 07/05/13 4:09 PM
 */
public class Rounding {
	public static void main(String[] args) {

	}
}
PQ.java

package tests;

import java.util.*;

/**
 * Shows how to use priority queues with custom comparators.
 *
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 15/11/12 11:13 AM
 */
public class PQ {
	static class Data {
		public int first;
		public int second;
	}

	public static void main(String[] args) {

		Comparator comparator = new Comparator(){
			@Override
			public int compare(final Data o1, final Data o2){
				// for smaller values having higher priority
				if ( o1.second > o2.second ) return 1;
				else if ( o1.second < o2.second ) return -1;
				return 0;
			}
		};

		Random generator = new Random();

		int initialCapacity = 10;
		PriorityQueue pq = new PriorityQueue(initialCapacity, comparator);

		for ( int a = 0; a < 10; a++ ) {
			Data tmp = new Data();
			tmp.first = generator.nextInt() % 1000;
			tmp.second = generator.nextInt() % 1000;
			pq.add(tmp);
		}

		System.out.println("all data:");
		Iterator iter = pq.iterator();
		while (iter.hasNext()) {
			Data tmp = iter.next();
			System.out.println(tmp.first + " " + tmp.second);
		}

		Data best = pq.peek();
		System.out.println("the best element: (" + best.first + ", " + best.second + ")");

		System.out.println("prioritised data:");
		Data tmp = pq.poll();
		while ( tmp != null ) {
			System.out.println(tmp.first + " " + tmp.second);
			tmp = pq.poll();
		}

	}
}
java2matlab.java

package tests;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 19/03/13 9:20 PM
 */

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/**
 * A very simple example that shows how to send commands to matlab line by line.
 */
public class java2matlab {

	public static void main(String[] args) throws Exception {
		Runtime rt = Runtime.getRuntime();
		Process p = rt.exec("matlab");
		BufferedReader input = new BufferedReader( new InputStreamReader(p.getInputStream()) );
		BufferedReader error = new BufferedReader( new InputStreamReader(p.getErrorStream()) );
		BufferedWriter output = new BufferedWriter( new OutputStreamWriter(p.getOutputStream()) );

		output.write("x=[0 2.6 5.1 7.4 9.6 7.8 4.8 2.6 0.1]\n");
		output.write("y=[-0.3 23.5 51.9 70.1 98.2 82.9 46.0 28.6 4.8]\n");
		output.write("R=corrcoef(x,y)\n");
		output.write("plot(x,y,'o');\n");
		output.flush();

		Thread.sleep(3000);

		while ( input.ready() ) {
			System.out.println( input.readLine() );
		}
		while (error.ready() ) {
			System.out.println( error.readLine() );
		}

		output.write("hold on\n");
		output.write("plot(x,y/2,'+');\n");
		output.flush();


		// the matlab process is killed on exit
		Thread.sleep(50000);
	}

}
googlejsonTest.java

package tests;

import com.google.gson.Gson;

import java.io.*;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 28/06/13 1:03 PM
 */
public class googlejsonTest {
	public static void main(String[] args) throws Exception {

		// create an object to serialise
		Student st = new Student();
		st._name = "John";
		st._courses = new String[10];
		st._courses[0] = "Linear Algebra";
		st._year = 2;

		// serialise the object
		OutputStream outputStream = new FileOutputStream("Student2.txt");
		Gson gson = new Gson();
		String str = gson.toJson(st);
		outputStream.write(str.getBytes());
		outputStream.close();

		// read in the object
		InputStream ips=new FileInputStream("Student2.txt");
		InputStreamReader ipsr=new InputStreamReader(ips);
		BufferedReader br=new BufferedReader(ipsr);
		String str2 = br.readLine();
		System.err.println(str2);
		Student st2 = gson.fromJson(str2, Student.class);

		// print the object
		System.out.println(st2._name);
		System.out.println(st2._year);
		System.out.println(Arrays.toString(st2._courses));
	}
}
MD5.java

package tests;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 22/07/14 11:44
 */
public class MD5 {

	public static String getMD5(String input) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] messageDigest = md.digest(input.getBytes());
			BigInteger number = new BigInteger(1, messageDigest);
			String hashtext = number.toString(16);
			// Now we need to zero pad it if you want the full 32 chars.
			while (hashtext.length() < 32) {
				hashtext = "0" + hashtext;
			}
			return hashtext;
		}
		catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}

	public static void main(String[] args) {
		String x = "Marek";
		System.out.println(getMD5(x));
		System.out.println(getMD5(x));
		x = "Gabrysia";
		System.out.println(getMD5(x));
	}
}
FileScan.java

package tests;

import java.io.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 23/11/12 11:48 AM
 */
public class FileScan {

	public static void main(String[] args) {

		try {
			FileInputStream fstream = new FileInputStream("data.txt");

			Scanner scanner = new Scanner(fstream);

			String str = scanner.next();

			int i = scanner.nextInt();

			System.out.println(str + "\t" + i);

			fstream.close();
		} catch (Exception e){
			System.err.println("Error: " + e.getMessage());
			e.printStackTrace();
			System.exit(1);
		}
	}
}
ReflectionAllFields.java

package tests;

import java.lang.reflect.Field;

/**
 * Shows how to print all fields of the object.
 * Found here: http://stackoverflow.com/questions/1526826/printing-all-variables-value-from-a-class
 *
 * User: Marek Grzes
 * Date: 31/03/14 14:07
 */
public class ReflectionAllFields {

	int x = 5;
	double y = 1000.8;
	String z = "hello world";
	public static String a = "a static field";

	public String toString() {
		StringBuilder result = new StringBuilder();
		String newLine = System.getProperty("line.separator");

		result.append( this.getClass().getName() );
		result.append( " Object {" );
		result.append(newLine);

		//determine fields declared in this class only (no fields of superclass)
		Field[] fields = this.getClass().getDeclaredFields();

		//print field names paired with their values
		for ( Field field : fields  ) {
			result.append("  ");
			try {
				result.append( field.getName() );
				result.append(": ");
				//requires access to private field:
				result.append( field.get(this) );
			} catch ( IllegalAccessException ex ) {
				System.out.println(ex);
			}
			result.append(newLine);
		}
		result.append("}");

		return result.toString();
	}

	public static void main(String[] args) {
		ReflectionAllFields r = new ReflectionAllFields();

		System.out.println(r.toString());
	}
}

// Program output

/*

tests.ReflectionAllFields Object {
  x: 5
  y: 1000.8
  z: hello world
  a: a static field
}

 */
PQMinMax.java

package tests;

import com.google.common.collect.MinMaxPriorityQueue;

import java.util.Iterator;
import java.util.Random;

/**
 * Shows how to use MinMaxPriorityQueue from google for bounded size priority queues.
 *
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 16/11/12 11:13 AM
 */
public class PQMinMax {

	static class Data implements Comparable {
		public int first;
		public int second;
		@Override
		public int compareTo(Data other){
			// for smaller values having higher priority
			if ( this.second > other.second ) return 1;
			else if ( this.second < other.second ) return -1;
			return 0;
		}
	}

	public static void main(String[] args) {

		Random generator = new Random();

		// set the max size to 5
		MinMaxPriorityQueue pq = MinMaxPriorityQueue.maximumSize(5).create();

		// pq.contains(); // <= certainly, this method is linear time, don't use it!

		System.out.println("adding data:");
		for ( int a = 0; a < 10; a++ ) {
			Data tmp = new Data();
			tmp.first = generator.nextInt() % 1000;
			tmp.second = generator.nextInt() % 1000;
			System.out.println(tmp.first + " " + tmp.second);
			pq.add(tmp);
		}

		System.out.println("all data:");
		Iterator iter = pq.iterator();
		while (iter.hasNext()) {
			Data tmp = iter.next();
			System.out.println(tmp.first + " " + tmp.second);
		}

		System.out.println("prioritised data:");
		Data tmp = pq.poll();
		while ( tmp != null ) {
			System.out.println(tmp.first + " " + tmp.second);
			tmp = pq.poll();
		}
	}
}
CustomSort.java

package tests;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 09/11/12 10:13 AM
 */

public class CustomSort {

	static class Data {
		public int first;
		public int second;
	}

	public static void main(String[] args) {
		Comparator comparator = new Comparator(){
			@Override
			public int compare(final Data o1, final Data o2){
				// for sorting in the ASC order
				if ( o1.second > o2.second ) return 1;
				else if ( o1.second < o2.second ) return -1;
				return 0;
			}
		};
		Random generator = new Random();
		Data[] arr = new Data[10];
		for ( int a = 0; a < arr.length; a++ ) {
			arr[a] = new Data();
			arr[a].first = a;
			arr[a].second = generator.nextInt();
		}

		Arrays.sort(arr, comparator);

		for ( int a = 0; a < arr.length; a++ ) {
			System.out.println(arr[a].first + "\t\t" + arr[a].second);
		}

	}
}
RunProcess.java

package tests;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 08/04/14 14:04
 */
public class RunProcess {
	public static void main(String[] args) throws Exception {

		Runtime run = Runtime.getRuntime();
		String[] cmd = {"/bin/sh", "-c", "ls -l /tmp" };
		Process process = run.exec(cmd);
		process.waitFor();

		// parse the result (output of the sub-process)
		BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
		String line;
		while ((line = input.readLine()) != null) {
			System.out.println(line);
		}
		input.close();

	}
}
RegExpressions.java

package tests;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 02/04/13 10:31 AM
 */
public class RegExpressions {
	public static void main(String[] args) {

		// replace all '_' with '\_'
		String str = "aaaaa-7_8";
		String str2 = str.replaceAll("_","\\\\_");
		System.out.println(str2);

		// remove from str3 everything up to >>> inclusive
		String str3 = "12:00 (x) >>> text";
		int pos = str3.indexOf(">>>");
		System.out.println(str3.substring(pos + 4, str3.length()));

		// replace all '\' with '\\'
		str = "aaaaa-7\\8";
		str2 = str.replaceAll("\\\\","\\\\\\\\");	// looks weird, doesn't it?
		System.out.println(str2);

		// replace all spaces with one space
		String line = "xxx    yyy        iii";
		line = line.replaceAll("\\s+"," ");
		System.out.println(line);
		// useful for split
		String[] tokens = line.split("\\s");
		for ( String token : tokens ) {
			System.out.println("token: " + token);
		}

	}
}
enumValues.java

package tests;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 31/03/14 13:15
 */
public class enumValues {

	public static enum Type1 {
		value1,
		value2;
	}

	public static void main(String[] args) {

		// print all types
		System.out.println(Arrays.toString(Type1.values()) );

		// get the value from string
		String tmp = "value2";
		Type1 x = Type1.valueOf(tmp);

		System.out.println(x.toString());

	}
}
jsonIOTest.java

package tests;

import com.cedarsoftware.util.io.JsonReader;
import com.cedarsoftware.util.io.JsonWriter;

import java.io.*;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 28/06/13 1:03 PM
 */
public class jsonIOTest {
	public static void main(String[] args) throws Exception {

		// create an object to serialise
		Student st = new Student();
		st._name = "John";
		st._courses = new String[10];
		st._courses[0] = "Linear Algebra";
		st._year = 2;

		// serialise the object
		OutputStream outputStream = new FileOutputStream("Student.txt");
		JsonWriter jw = new JsonWriter(outputStream);
		jw.write(st);
		jw.close();

		// read in the object
		InputStream inputStream = new FileInputStream("Student.txt");
		JsonReader jr = new JsonReader(inputStream);
		Student st2 = (Student) jr.readObject();

		// print the object
		System.out.println(st2._name);
		System.out.println(st2._year);
		System.out.println(Arrays.toString(st2._courses));
		jr.close();
	}
}
SimpleXMLTest.java

package tests;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import java.io.File;
import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 28/06/13 9:57 PM
 */
public class SimpleXMLTest {

	public static void main(String[] args) throws Exception {

		// create an object to serialise
		Student st = new Student();
		st._name = "John";
		st._courses = new String[10];
		st._courses[0] = "Linear Algebra";
		st._year = 2;

		// serialise to the xml file
		Serializer serializer = new Persister();
		File result = new File("Student3.xml");
		serializer.write(st, result);

		// load from the xml file
		File source = new File("Student3.xml");
		Student st2 = serializer.read(Student.class, source);

		// print the object
		System.out.println(st2._name);
		System.out.println(st2._year);
		System.out.println(Arrays.toString(st2._courses));
		System.out.println(st2._x);

	}
}
JDBCTest.java

package tests;

import java.sql.*;

/**
 * In Ubuntu, the jdbc jar file is here /usr/share/java/mysql-connector-java after the appropriate package is installed.
 *
 * User: Marek Grzes
 * Date: 08/07/13 3:18 PM
 */
public class JDBCTest {
	public static void main(String[] args) {
		String user = args[0];
		String passwd = args[1];
		String url = args[2];

		try {
			// Load the database driver
			Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" ) ;

			// Get a connection to the database
			Connection connect = DriverManager.getConnection(url, user, passwd);

			Statement statement = connect.createStatement();
			// Result set get the result of the SQL query
			ResultSet resultSet = statement.executeQuery("select * from ttest.pet");

			System.out.println("Table: " + resultSet.getMetaData().getTableName(1));
			for  (int i = 1; i<= resultSet.getMetaData().getColumnCount(); i++){
				System.out.println("Column " +i  + " "+ resultSet.getMetaData().getColumnName(i));
			}

			while(resultSet.next()){
				//Retrieve by column name
				System.out.println(resultSet.getString("name") + "\t" + resultSet.getString("owner"));
			}
			resultSet.close();

			connect.close() ;
		}
		catch( SQLException se ) {
			System.out.println( "SQL Exception:" ) ;

			// Loop through the SQL Exceptions
			while( se != null ) {
				System.out.println( "State  : " + se.getSQLState()  ) ;
				System.out.println( "Message: " + se.getMessage()   ) ;
				System.out.println( "Error  : " + se.getErrorCode() ) ;
				se = se.getNextException() ;
			}
		}
		catch( Exception e ) {
			System.out.println( e ) ;
		}
	}
}
HashMapTest.java

package tests;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 14/02/13 9:33 PM
 */
public class HashMapTest {

	public static void main(String[] args) {
		HashMap map = new HashMap();

		map.put(1, 2);
		map.put(2, 4);

		Integer x = map.get(5);

		if ( x == null ) {
			System.out.println("null");
		}

		// entrySet() returns a Set view of the mappings contained in this map, so the new set is not created!
		for (Map.Entry item : map.entrySet()) {
			Integer key = item.getKey();
			Integer value = item.getValue();
			System.out.println(key + " - " + value);
		}
	}

}
OutOfMemory.java

package tests;

import java.util.LinkedList;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 13/06/14 15:09
 */
public class OutOfMemory {
	public static void main(String[] args) {

		double[] x;
		LinkedList list = new LinkedList();
		for ( int i = 0; i < 1000000000; i++) {
			x = new double[10000];
			list.add(x);
		}
	}
}
IterateAndRemoveFromCollection.java

package tests;

import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 09/11/12 2:36 PM
 */
public class IterateAndRemoveFromCollection {
	public static void main(String[] args) {
		List list = new LinkedList(Arrays.asList(1, 2, 3, 4, 5));
		System.out.println(list.toString());
		Iterator i = list.iterator();
		while(i.hasNext()){
			int val = i.next();
			if ( val == 3 ) {
				// remove using the iterator instead of the list object
				i.remove();
			}
		}
		System.out.println(list);
	}
}
ApacheCLIExample.java

package tests;

import mgjcommon.Pair;
import org.apache.commons.cli.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 13/01/14 09:33 AM
 *
 * Shows how to use apache command line interface.
 */
public class ApacheCLIExample {

	public static class ExOptionGroup {
		static public boolean _help = false;
		static public double _num = 0;

		public static OptionGroup getOptionGroup() {
			OptionGroup group = new OptionGroup();
			group.addOption( OptionBuilder.withLongOpt( "num" ).withDescription(
					"description of a numerical parameter"
			).hasArg().withArgName("NUM").create() );
			Option help = new Option("h", "help", false, "print help and exit");
			group.addOption( help );
			return group;
		}

		public static void readOptions(CommandLine line) throws Exception {
			if ( line.hasOption("num") ) {
				_num = Double.parseDouble(line.getOptionValue("alg-class"));
			}
			if (line.hasOption("help")) {
				_help =  true;
			}
		}

		public static List> exampleCalls() {
			List> res = new ArrayList>();
			Pair tmp = new Pair(null, null);
			tmp.first = "with help ";
			tmp.second = "--num 0.5 --help";
			res.add(tmp);
			tmp = new Pair(null, null);
			tmp.first = "no help";
			tmp.second = "--num 0.5";
			res.add(tmp);
			return res;
		}

		public static void logArgs(String[] args) {
			System.out.print("program arguments: [ ");
			for ( String s : args ) {
				System.out.print(s + " ");
			}
			System.out.println("]");
		}
	}
	public static void main(String[] args) throws Exception {

		// ----- log arguments
		ExOptionGroup.logArgs(args);

		// create the command line parser
		CommandLineParser parser = new PosixParser();

		// create the Options
		Options options = new Options();

		// load all option groups
		options.addOptionGroup(ExOptionGroup.getOptionGroup());

		// parse the command line arguments
		CommandLine line = parser.parse(options, args);

		// load parameters in all groups using the line object
		ExOptionGroup.readOptions(line);

		if ( ExOptionGroup._help ) {
			HelpFormatter formatter = new HelpFormatter();
			formatter.printHelp(120, "java program ", "OPTIONS:", options, "");

			// print example calls
			System.out.println("\nEXAMPLE CALLS:\n");
			List> example_calls = new ArrayList>();
			List> tmp;
			tmp = ExOptionGroup.exampleCalls();
			if ( tmp != null ) {
				example_calls.addAll(tmp);
			}
			// read from other groups here

			for (Pair s : example_calls) {
				System.out.println(s.first);
				System.out.println("\tjava program " + s.second + "\n");
			}

		}
		// -----

	}
}
FileReadWrite.java

package tests;

import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 23/11/12 11:32 AM
 */
public class FileReadWrite {

	public static void main(String[] args) {

		String s = new String();

		try{
			InputStream ips=new FileInputStream("data.txt");
			InputStreamReader ipsr=new InputStreamReader(ips);
			BufferedReader br=new BufferedReader(ipsr);
			String line;
			while ((line=br.readLine())!=null){
				System.out.println(line);
				s = s + line;
			}
			br.close();

			BufferedReader br2=new BufferedReader( new InputStreamReader( new FileInputStream("data.txt") ) );

		}
		catch (Exception e) {
			System.err.println(e.toString());
			System.exit(1);
		}

		try {
			FileWriter fw = new FileWriter ("out.txt");
			BufferedWriter bw = new BufferedWriter (fw);
			PrintWriter fileOut = new PrintWriter (bw);
			fileOut.println ("[" + s + "]");
			fileOut.flush();
			fileOut.close();

			PrintWriter fileWriter = new PrintWriter( new BufferedWriter( new FileWriter ( "x.txt" ) ) );

		}
		catch (Exception e){
			System.err.println(e.toString());
			System.exit(1);
		}

		// useful when PrintWriter is a parameter and we want to build a string
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		pw.println("StringWriter test");
		System.out.println(sw.toString());

	}

}
TIntSetTest.java

package tests;

import gnu.trove.procedure.TIntProcedure;
import gnu.trove.set.hash.TIntHashSet;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 22/02/13 11:49 AM
 */

public class TIntSetTest {

	// example procedure that can have access to external data
	static class MyTIntProcedure implements TIntProcedure {
		int sum = 0;
		@Override
		public boolean execute(final int value) {
			sum += value;
			System.out.println(value);
			System.out.println("current sum: " + sum);
			// has to return true, for each is stopped when false is returned for the first time
			return true;
		}
	}

	public static void main(String[] args) {
		TIntHashSet iset = new TIntHashSet();

		iset.add(9);
		iset.add(11);
		iset.add(4);

		// access to raw data: forEach and iterator do not do anything clever and iterate over these arrays
		for ( int a : iset._set ) {
			System.out.println(a);
		}
		for ( int s : iset._states ) {
			System.out.println(s);
		}

		iset.forEach(new TIntProcedure() {
			@Override
			public boolean execute(final int value) {
				System.out.println(value);
				// has to return true, for each is stopped when false is returned for the first time
				return true;
			}
		});

		iset.forEach(new MyTIntProcedure());
	}
}
TIntMapTest.java

package tests;

import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TObjectIntHashMap;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 07/05/13 9:58 AM
 */
public class TIntMapTest {
	public static void main(String[] args) throws Exception {
		TObjectIntHashMap map = new TObjectIntHashMap();

		map.put("str1", 10);

		int x = map.get("str2");

		if ( !map.containsKey("str2") ) {
			System.err.println("does not contain the key");
		}

		System.err.println(x);

	}
}
Student.java

package tests;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 28/06/13 1:04 PM
 */
public class Student {
	public String _name;
	public String[] _courses;
	public int _year;
	public double _x = Double.NaN;
}
LinkedListTest.java

package tests;

import java.util.LinkedList;

/**
 * Created with IntelliJ IDEA.
 * User: Marek Grzes
 * Date: 14/02/13 3:19 PM
 */

/**
 * @see IterateAndRemoveFromCollection how to remove from a double linked list
 */
public class LinkedListTest {
	public static void main(String[] args) {
		LinkedList list = new LinkedList();

		list.addLast(1);
		list.addLast(2);
		System.out.println(list.toString());

		list.addFirst(3);
		System.out.println(list.toString());

		// be careful, push puts a new element at the front of the list !!!
		list.push(7);
		System.out.println(list.toString());

	}
}


Back to main page