Posts Tagged ‘java’

Java: The Class class

From aau.dk

The java.lang.Class Class
• There is a Class object for each class in your system.
• The way Java type information is represented at run-time.
• Information for Class object is stored in a .class file
• Load when first object is created or static access
• The Class object is used to create all the objects of that class.
• The Java Virual Machine (JVM) finds the appropriate .class file
and loads it as a Class object the first time you need that class.
• Goes through the directories listed in the CLASSPATH
Java

Mean and Multi-modal Mean Functions (methods) for Java

When it comes to stats Java ain’t no R. Still, we can do anything in one language that we can do in another.

Let’s have a look at some mean functions for Java, to illustrate:

public static double mean(double[] m) {
     double sum = 0;
     for (int i = 0; i < m.length; i++) {
         sum += m[i];
     }
    return sum / m.length;}
For multi-modal:
public static List<Integer> mode(final int[] a) {
     final List<Integer> modes = new ArrayList<Integer>();
     final Map<Integer, Integer> countMap = new HashMap<Integer, Integer>();

     int max = -1;

     for (final int n : numbers) {
         int count = 0;

         if (countMap.containsKey(n)) {
             count = countMap.get(n) + 1;
         } else {
             count = 1;
         }

         countMap.put(n, count);

         if (count > max) {
             max = count;
         }
     }

     for (final Map.Entry<Integer, Integer> tuple : countMap.entrySet()) {
         if (tuple.getValue() == max) {
             modes.add(tuple.getKey());
         }
     }

     return modes;}

Java

Read int from stdin all in just 1 Line (Java 6 or higher)

int n = Integer.parseInt(System.console().readLine());
Note that that under most IDEs System.console will return NULL when the application is invoked via a launcher making it hard to debug.

FAQ: What are “Factory methods” and “Factory patterns” in Java?

An odd concept to some, but it’s actually quite straightforward — these are methods (functions) that are declared to return instances of some base class (especially an abstract base class) but actually return instances of a derived class are often called “Factory Methods“, because they produce objects.
The associated design pattern is called the Factory Pattern. Using the Factory pattern is an excellent way to hide implementation details from parts of a program that don’t need to know them. This kind of hiding tremendously simplifies program maintenance.
Java

Java: Determine if String is a URL/URI or file

In the spirit of making a more polymorphous app, you may need to pull off this trick, as I did in a recent assignment at Berkeley. I compiled a few different ways of getting the job done:
public boolean isLocalFile(String file) {
     try {
         new URL(file);
         return false;
     } catch (MalformedURLException e) {
         return true;
    }}
there’s also a util for this in Android’s toolkit (not worth grabbing unless you’re specifically writing for Android, though).
another semi-related thing;
  1. Make sure the filename is correct (proper capitalization, matching extension etc – as already suggested).
  2. Use the Class.getResource method to locate your file in the classpath – don’t rely on the current directory:
    URL url = insertionSort.class.getResource("10_Random");
    
    File file = new File(url.toURI());
  3. Specify the absolute file path via command-line arguments:
    File file = new File(args[0]);

In Eclipse:

  1. Choose “Run configurations”
  2. Go to the “Arguments” tab
  3. Put your “c:/Users/HackR/somewhere/10_myjava.txt.or.something” into the “Program arguments” section

Java

Java: How to import StAX libraries for parsing XML

In short:

 

import javax.xml.stream.*;
import java.io.*;
import java.util.*;//usually, but not always needed

In long:

Here are steps in writing code to parse an XML document with StAX.

  1. Import the following libraries:
     import javax.xml.stream.*;
     import java.io.*;
  1. Create an XMLInputFactory . See the read() method above.
  2. Create an XMLStreamReader and pass a Reader to it such as a FileReader. The XML file is passed as a parameter to FileReader.
  3. We can now iterate through the contents of our XML file using the streamreader’s next() method.
  4. next() returns an event code that indicates which part of the document has been read such as: DTD, START_ELEMENT, CHARACTERS and END_ELEMENT.
  5. If you get the START_ELEMENT event code, you can retrieve the element’s name using the getLocalName() method. To read the attributes, use getAttributeValue() method.
  6. To read the text between the start and end tags, wait until you receive the CHARACTERS event code. Afterwards, you can read the text using getText().

Thanks to my instructor Carl Limsico for the step-by-step!

Quick Tip: Java Heap Space Fix for any Jar File in 1 Line

 java -Xmx512m -jar yourjar.jar 

where 512m is for 512MB and which can be increased as needed.