posted by 쁘로그래머 2018. 12. 22. 16:41

우분투에서 자바(Java) 설치하는 방법입니다.

우선 우분투에는 기본적으로 JAVA가 설치되어 있습니다~

따라서 먼저 어떠한 JAVA가 설치되어 있는지 확인합니다.


# JAVA 설치 확인

$ sudo apt-get update

$ java -version


# JAVA 설치 방법

아래 명령어는 현재 default로 설정된 자바를 설치합니다.

$ sudo apt-get install default-jdk

$ sudo apt-get install default-jre (jre만을 원한다면)


원하는 자바가 설치되어 있지 않다면, 아래 내용을 참조하세요.

# Open JAVA 설치

$ sudo apt-get install openjdk-8-jdk

$ sudo apt-get install openjdk-8-jre (jre만을 원한다면)


# JAVA 환경변수 지정

환경변수를 지정하기 위해, Path를 알아야 합니다.

JAVA관리를 위한 명령어를 통하면, 각 JAVA들의 path를 확인할 수 있습니다.


$ sudo nano /etc/environment

JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64"


저장을 하고 나서, 아래 명령어로 적용을 해주면 됩니다.

$ source /etc/environment


PATH가 제대로 지정되었는지 확인하기 위해서는 아래 명령을 사용합니다.

$ echo $JAVA_HOME


posted by 쁘로그래머 2018. 6. 28. 19:12

# Question

How do I generate a random int value in a specific range?

I have tried the following, but those do not work:

Attempt 1:

randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.

Attempt 2:

Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.

# Answer

In Java 1.7 or later, the standard way to do this is as follows:

import java.util.concurrent.ThreadLocalRandom;

// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1);

See the relevant JavaDoc. This approach has the advantage of not needing to explicitly initialize a java.util.Random instance, which can be a source of confusion and error if used inappropriately.

However, conversely there is no way to explicitly set the seed so it can be difficult to reproduce results in situations where that is useful such as testing or saving game states or similar. In those situations, the pre-Java 1.7 technique shown below can be used.

Before Java 1.7, the standard way to do this is as follows:

import java.util.Random;

/**
 * Returns a pseudo-random number between min and max, inclusive.
 * The difference between min and max can be at most
 * <code>Integer.MAX_VALUE - 1</code>.
 *
 * @param min Minimum value
 * @param max Maximum value.  Must be greater than min.
 * @return Integer between min and max, inclusive.
 * @see java.util.Random#nextInt(int)
 */
public static int randInt(int min, int max) {

    // NOTE: This will (intentionally) not run as written so that folks
    // copy-pasting have to think about how to initialize their
    // Random instance.  Initialization of the Random instance is outside
    // the main scope of the question, but some decent options are to have
    // a field that is initialized once and then re-used as needed or to
    // use ThreadLocalRandom (if using at least Java 1.7).
    // 
    // In particular, do NOT do 'Random rand = new Random()' here or you
    // will get not very good / not very random results.
    Random rand;

    // nextInt is normally exclusive of the top value,
    // so add 1 to make it inclusive
    int randomNum = rand.nextInt((max - min) + 1) + min;

    return randomNum;
}

See the relevant JavaDoc. In practice, the java.util.Random class is often preferable to java.lang.Math.random().

In particular, there is no need to reinvent the random integer generation wheel when there is a straightforward API within the standard library to accomplish the task.


source: https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java

posted by 쁘로그래머 2018. 6. 28. 19:10

# Question

I have an array that is initialized like:

Element[] array = {new Element(1), new Element(2), new Element(3)};

I would like to convert this array into an object of the ArrayList class.

ArrayList<Element> arraylist = ???;


# Answer

Given:

Element[] array = new Element[] { new Element(1), new Element(2), new Element(3) };

The simplest answer is to do:

List<Element> list = Arrays.asList(array);

This will work fine. But some caveats:

  1. The list returned from asList has fixed size. So, if you want to be able to add or remove elements from the returned list in your code, you'll need to wrap it in a new ArrayList. Otherwise you'll get an UnsupportedOperationException.
  2. The list returned from asList() is backed by the original array. If you modify the original array, the list will be modified as well. This may be surprising.


source: https://stackoverflow.com/questions/157944/create-arraylist-from-array

posted by 쁘로그래머 2018. 6. 28. 19:07

# Question

What are the differences between a HashMap and a Hashtable in Java?

Which is more efficient for non-threaded applications?

# Answer

There are several differences between HashMap and Hashtable in Java:

  1. Hashtable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.

  2. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values.

  3. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.

Since synchronization is not an issue for you, I'd recommend HashMap. If synchronization becomes an issue, you may also look at ConcurrentHashMap.

source: https://stackoverflow.com/questions/40471/differences-between-hashmap-and-hashtable

posted by 쁘로그래머 2018. 6. 28. 19:05

# Question

If you have a java.io.InputStream object, how should you process that object and produce a String?


Suppose I have an InputStream that contains text data, and I want to convert it to a String, so for example I can write that to a log file.

What is the easiest way to take the InputStream and convert it to a String?

public String convertStreamToString(InputStream is) { 
    // ???
}


# Answer

A nice way to do this is using Apache commons IOUtils to copy the InputStream into a StringWriter... something like

StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer, encoding);
String theString = writer.toString();

or even

// NB: does not close inputStream, you'll have to use try-with-resources for that
String theString = IOUtils.toString(inputStream, encoding); 

Alternatively, you could use ByteArrayOutputStream if you don't want to mix your Streams and Writers


source: https://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string