Categorías
Basics

Ejemplo simple para mostrar cómo usar el formato de fecha en Java

La siguiente es una pregunta del «Programador certificado por SCJP Sun para el examen de la guía de estudio de Java 6» por Kathy Sierra y Bert Bates. Personalmente, no creo que esta sea una buena pregunta, pero es bueno saber cómo usar la clase DateFormat.

Dado que 1119280000000L es aproximadamente el número de milisegundos desde el 1 de enero de 1970 hasta el 20 de junio de 2005, y que desea imprimir esa fecha en alemán, utilizando el estilo LARGO de modo que «junio» se muestre como «Juni».

import java.text.*;
import java.util.*;
//import java.date.*;// There is such package defined in Java!!
public class DateFormatExample {
    public static void main(String[] args){
        Date d = new Date(1119280000000L);
        DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.GERMANY);
        System.out.println(df.format(d));
    }
}

Categorías
Collections

Práctica sencilla con Scanner en Java

¿Cuál es el resultado del siguiente programa?

import java.util.Scanner;
public class Looking {
    public static void main(String[] args){
        String input = "1 2 a 3 45 6";
        Scanner sc = new Scanner(input);
        int x = 0;
        do{
            x = sc.nextInt();
            System.out.print(x + " ");
        }while(x != 0);
    }
}

El siguiente es el resultado:

run:
Exception in thread "main" java.util.InputMismatchException
        at java.util.Scanner.throwFor(Scanner.java:840)
        at java.util.Scanner.next(Scanner.java:1461)
        at java.util.Scanner.nextInt(Scanner.java:2091)
        at java.util.Scanner.nextInt(Scanner.java:2050)
        at Looking.main(Looking.java:19)
1 2 Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

Los métodos nextXxx () generalmente se invocan después de una llamada a hasNextXxx (), que determina si el siguiente token es del tipo correcto. Aquí no existe tal método, por lo que se lanza una excepción. (Java.util.InputMismatchException)

El siguiente es el código corregido:

public class Looking {
    public static void main(String[] args){
        String input = "1 2 a 3 45 6";
        Scanner sc = new Scanner(input);
        int x = 0;
        while(sc.hasNextInt()){
            x = sc.nextInt();
            System.out.print(x + " ");
        }
    }
}

El resultado es:

run:
1 2 BUILD SUCCESSFUL (total time: 0 seconds)

Categorías
Collections Diagram

La interfaz y el diagrama de jerarquía de clases de las colecciones de Java

1. Colección vs colecciones

En primer lugar, «Colección» y «Colecciones» son dos conceptos diferentes. Como verá en el diagrama de jerarquía a continuación, «Colección» es una interfaz raíz en la jerarquía de Colección, pero «Colecciones» es una clase que proporciona métodos estáticos para manipular algunos tipos de Colección.

2. Jerarquía de clases de la colección

El siguiente diagrama muestra la jerarquía de clases de Collection.

3. Jerarquía de clases de Map

Aquí está la jerarquía de clases de Map.

4. Resumen de clases

resumen de la colección

5. Ejemplo de código

El siguiente es un ejemplo simple para ilustrar algunos tipos de colección:

List<String> a1 = new ArrayList<String>();
a1.add("Program");
a1.add("Creek");
a1.add("Java");
a1.add("Java");
System.out.println("ArrayList Elements");
System.out.print("t" + a1 + "n");
 
List<String> l1 = new LinkedList<String>();
l1.add("Program");
l1.add("Creek");
l1.add("Java");
l1.add("Java");
System.out.println("LinkedList Elements");
System.out.print("t" + l1 + "n");
 
Set<String> s1 = new HashSet<String>(); // or new TreeSet() will order the elements;
s1.add("Program");
s1.add("Creek");
s1.add("Java");
s1.add("Java");
s1.add("tutorial");
System.out.println("Set Elements");
System.out.print("t" + s1 + "n");
 
Map<String, String> m1 = new HashMap<String, String>(); // or new TreeMap() will order based on keys
m1.put("Windows", "2000");
m1.put("Windows", "XP");
m1.put("Language", "Java");
m1.put("Website", "programcreek.com");
System.out.println("Map Elements");
System.out.print("t" + m1);

Producción:

ArrayList Elements
	[Program, Creek, Java, Java]
LinkedList Elements
	[Program, Creek, Java, Java]
Set Elements
	[tutorial, Creek, Program, Java]
Map Elements
	{Windows=XP, Website=programcreek.com, Language=Java}

Categorías
Collections

Ejemplo de ordenación de matrices

import java.util.Arrays;
import java.util.Comparator;
 
public class SearchObjArray {
    public static void main(String[] args){
        String [] sa = {"one", "two", "three", "four"};
        Arrays.sort(sa);
        for(String s : sa){
            System.out.print(s + " ");
        }
        System.out.println("none = " + Arrays.binarySearch(sa, "one"));
 
        System.out.println("now reverse sort");
        ReSortComparator rs = new ReSortComparator();
        Arrays.sort(sa, rs);//re-sort the array using the Comparator. sort(sa, rs)
        for(String s : sa){
            System.out.print(s + " ");
        }
        System.out.println("none = " + Arrays.binarySearch(sa, "one"));//doesn't pass the binarySearch() method the Comparator we used to sort the array, so get an incorrect answer
        System.out.println("one = " + Arrays.binarySearch(sa,"one", rs));//passing the Comparator to binarySearch(), so get correct answer
    }
    static class ReSortComparator implements Comparator{//define the Comparator, it's ok for this to be an inner class
        public int compare(String a, String b){
            return b.compareTo(a);
        }
    }
}

Producción:

correr:
cuatro uno tres dos
uno = 1
ahora orden inverso
dos tres uno cuatro
uno = -1
uno = 2
CONSTRUYE EXITOSO (tiempo total: 2 segundos)

Categorías
Collections

Ejemplo de clase Java PriorityQueue

En Java, el PriorityQueue La clase se implementa como un montón de prioridad. Heap es una estructura de datos importante en informática. Para obtener una descripción general rápida del montón, aquí es un muy buen tutorial.

1. Ejemplo simple

Los siguientes ejemplos muestran las operaciones básicas de PriorityQueue como offer (), peek (), poll () y size ().

import java.util.Comparator;
import java.util.PriorityQueue;
 
public class PriorityQueueTest {
 
	static class PQsort implements Comparator<Integer> {
 
		public int compare(Integer one, Integer two) {
			return two - one;
		}
	}
 
	public static void main(String[] args) {
		int[] ia = { 1, 10, 5, 3, 4, 7, 6, 9, 8 };
		PriorityQueue<Integer> pq1 = new PriorityQueue<Integer>();
 
		// use offer() method to add elements to the PriorityQueue pq1
		for (int x : ia) {
			pq1.offer(x);
		}
 
		System.out.println("pq1: " + pq1);
 
		PQsort pqs = new PQsort();
		PriorityQueue<Integer> pq2 = new PriorityQueue<Integer>(10, pqs);
		// In this particular case, we can simply use Collections.reverseOrder()
		// instead of self-defined comparator
		for (int x : ia) {
			pq2.offer(x);
		}
 
		System.out.println("pq2: " + pq2);
 
		// print size
		System.out.println("size: " + pq2.size());
		// return highest priority element in the queue without removing it
		System.out.println("peek: " + pq2.peek());
		// print size
		System.out.println("size: " + pq2.size());
		// return highest priority element and removes it from the queue
		System.out.println("poll: " + pq2.poll());
		// print size
		System.out.println("size: " + pq2.size());
 
		System.out.print("pq2: " + pq2);
 
	}
}

Producción:

pq1: [1, 3, 5, 8, 4, 7, 6, 10, 9]
pq2: [10, 9, 7, 8, 3, 5, 6, 1, 4]
size: 9
peek: 10
size: 9
poll: 10
size: 8
pq2: [9, 8, 7, 4, 3, 5, 6, 1]

2. Ejemplo de resolución de problemas con PriorityQueue

Fusión de k lista ordenada.

Para obtener más detalles sobre PriorityQueue, vaya a Doc.

Categorías
Generics

Un problema de ejemplo de tipos genéricos

El siguiente código tiene errores de compilación. Es confuso porque piensa en algún lugar para encontrar el problema.

import java.util.*;
abstract class Animal{
    public abstract void checkup();
}
class Dog extends Animal{
    public void checkup(){
        System.out.println("Dog checkup");
    }
}
class Cat extends Animal{
    public void checkup(){
        System.out.println("Cat checkup");
    }
}
class Bird extends Animal{
    public void checkup(){
        System.out.println("Bird checkup");
    }
}
public class AnimalDoctorGeneric {
    private void checkAnimals(ArrayList<Animal> animals){
        for(Animal a : animals){
            a.checkup();
        }
    }
    private void addAnimals(List<Animal> animals){
        animals.add(new Dog());
    }
    public static void main(String [] args){
        List<Animal> animals = new ArrayList<Animal>();
        animals.add(new Dog());
        animals.add(new Dog());
        AnimalDoctorGeneric doc = new AnimalDoctorGeneric();
        doc.addAnimals(animals);
        doc.checkAnimals(animals);// error here!!!!
        //doc.checkAnimals((ArrayList<Animal>) animals); this line is the correct code
        //to use checkAnimals method, the argument has to be correct type. 
        //System.out.println(animals.get(1) + " " + animals.get(2));
    }
}

Para arreglar el código, la forma más fácil es lanzar animales a ArrayList. Entonces, para cambiar la línea 36 a:
doc.checkAnimals ((ArrayList) animales);

La razón es que la clase ArrayList implementa la interfaz List, son diferentes, List debe convertirse en ArrayList para satisfacer el método checkAnimals (ArrayList animales).

Categorías
Real Methods

Java: convertir imagen en matriz de bytes, convertir matriz de bytes en imagen

Esta publicación muestra dos formas diferentes de convertir una imagen en una matriz de bytes y convertir una matriz de bytes en una imagen.

En primer lugar, el tipo de byte en Java es un entero de complemento a dos con signo de 8 bits. Su rango es [-128, 127]. Una matriz de bytes es solo una matriz de bytes. Una imagen es esencialmente un archivo. Entonces, la tarea es convertir el archivo en una matriz para que pueda almacenarse o transferirse más fácilmente en diferentes tipos de aplicaciones.

1. Método 1

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
 
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
 
public class ConvertImage {
 
    public static void main(String[] args) throws FileNotFoundException, IOException {
    	/*
    	 * 1. How to convert an image file to  byte array?
    	 */
 
        File file = new File("C:rose.jpg");
 
        FileInputStream fis = new FileInputStream(file);
        //create FileInputStream which obtains input bytes from a file in a file system
        //FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.
 
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                //Writes to this byte array output stream
                bos.write(buf, 0, readNum); 
                System.out.println("read " + readNum + " bytes,");
            }
        } catch (IOException ex) {
            Logger.getLogger(ConvertImage.class.getName()).log(Level.SEVERE, null, ex);
        }
 
        byte[] bytes = bos.toByteArray();
 
        /*
         * 2. How to convert byte array back to an image file?
         */
 
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        Iterator<?> readers = ImageIO.getImageReadersByFormatName("jpg");
 
        //ImageIO is a class containing static methods for locating ImageReaders
        //and ImageWriters, and performing simple encoding and decoding. 
 
        ImageReader reader = (ImageReader) readers.next();
        Object source = bis; 
        ImageInputStream iis = ImageIO.createImageInputStream(source); 
        reader.setInput(iis, true);
        ImageReadParam param = reader.getDefaultReadParam();
 
        Image image = reader.read(0, param);
        //got an image file
 
        BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB);
        //bufferedImage is the RenderedImage to be written
 
        Graphics2D g2 = bufferedImage.createGraphics();
        g2.drawImage(image, null, null);
 
        File imageFile = new File("C:newrose2.jpg");
        ImageIO.write(bufferedImage, "jpg", imageFile);
 
        System.out.println(imageFile.getPath());
    }
}

2. Método 2

La siguiente es una versión más simple que hace lo mismo. Utiliza la clase BufferedImage, que es una forma probada más eficiente.

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
 
 
public class SimpleConvertImage {
	public static void main(String[] args) throws IOException{
		String dirName="C:";
		ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
		BufferedImage img=ImageIO.read(new File(dirName,"rose.jpg"));
		ImageIO.write(img, "jpg", baos);
		baos.flush();
 
		String base64String=Base64.encode(baos.toByteArray());
		baos.close();
 
		byte[] bytearray = Base64.decode(base64String);
 
		BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytearray));
		ImageIO.write(imag, "jpg", new File(dirName,"snap.jpg"));
	}
}

3. Enlaces de descarga

Puede descargar el código del método 1 y el método 2.

Categorías
Real Methods

Java: convierta un archivo en una matriz de bytes, luego convierta la matriz de bytes en un archivo.

En esta publicación, le mostraré cómo convertir un archivo en una matriz de bytes y luego convertir una matriz de bytes en un archivo.

Para convertir un archivo en una matriz de bytes, se usa la clase ByteArrayOutputStream. Esta clase implementa un flujo de salida en el que los datos se escriben en una matriz de bytes. El búfer crece automáticamente a medida que se escriben datos en él. Los datos se pueden recuperar usando toByteArray () y toString ().

Para convertir la matriz de bytes de nuevo al archivo original, se usa la clase FileOutputStream. Un flujo de salida de archivo es un flujo de salida para escribir datos en un archivo o en un descriptor de archivo.

El siguiente código ha sido completamente probado.

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
 
public class genFile {
 
    public static void main(String[] args) throws FileNotFoundException, IOException {
        File file = new File("java.pdf");
 
        FileInputStream fis = new FileInputStream(file);
        //System.out.println(file.exists() + "!!");
        //InputStream in = resource.openStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        try {
            for (int readNum; (readNum = fis.read(buf)) != -1;) {
                bos.write(buf, 0, readNum); //no doubt here is 0
                //Writes len bytes from the specified byte array starting at offset off to this byte array output stream.
                System.out.println("read " + readNum + " bytes,");
            }
        } catch (IOException ex) {
            Logger.getLogger(genJpeg.class.getName()).log(Level.SEVERE, null, ex);
        }
        byte[] bytes = bos.toByteArray();
 
        //below is the different part
        File someFile = new File("java2.pdf");
        FileOutputStream fos = new FileOutputStream(someFile);
        fos.write(bytes);
        fos.flush();
        fos.close();
    }
}

¿Por qué alguien querría convertir un archivo en una matriz de bytes?

Hay varias aplicaciones de esta conversión. Por ejemplo, convierta el archivo en byte para guardarlo en la base de datos, transfiera el archivo a otro sistema usando el servicio web, etc.

Del mismo modo, puede convertir una imagen en una matriz de bytes, consulte esta publicación.

ACTUALIZACIÓN (16/12/2015):
Existe un método muy conveniente de com.google.common.io.FilestoByteArray(). Vea algunos ejemplos aquí.

Referencias:

1. ByteArrayOutputStream Java Doc
2. FileOutputStream Java Doc

Categorías
Collections

Un ejemplo sencillo de TreeSet

El siguiente es un ejemplo de TreeSet muy simple. De este simple ejemplo, verá:

  • TreeSet está ordenado
  • Cómo iterar un TreeSet
  • Cómo comprobar que está vacío
  • Cómo recuperar el primer / último elemento
  • Cómo eliminar un elemento

Si desea saber más sobre la Colección Java, consulte el diagrama de jerarquía de la Colección Java.

import java.util.Iterator;
import java.util.TreeSet;
 
public class TreeSetExample {
 
   public static void main(String[] args) {
	System.out.println("Tree Set Example!n");
	TreeSet<Integer> tree = new TreeSet<Integer>();
	tree.add(12);
	tree.add(63);
	tree.add(34);
	tree.add(45);
 
	// here it test it's sorted, 63 is the last element. see output below
	Iterator<Integer> iterator = tree.iterator();
	System.out.print("Tree set data: ");
 
	// Displaying the Tree set data
	while (iterator.hasNext()) {
		System.out.print(iterator.next() + " ");
	}
	System.out.println();
 
	// Check empty or not
	if (tree.isEmpty()) {
		System.out.print("Tree Set is empty.");
	} else {
		System.out.println("Tree Set size: " + tree.size());
	}
 
	// Retrieve first data from tree set
	System.out.println("First data: " + tree.first());
 
	// Retrieve last data from tree set
	System.out.println("Last data: " + tree.last());
 
	if (tree.remove(45)) { // remove element by value
		System.out.println("Data is removed from tree set");
	} else {
		System.out.println("Data doesn't exist!");
	}
	System.out.print("Now the tree set contain: ");
	iterator = tree.iterator();
 
	// Displaying the Tree set data
	while (iterator.hasNext()) {
		System.out.print(iterator.next() + " ");
	}
	System.out.println();
	System.out.println("Now the size of tree set: " + tree.size());
 
	// Remove all
	tree.clear();
	if (tree.isEmpty()) {
		System.out.print("Tree Set is empty.");
	} else {
		System.out.println("Tree Set size: " + tree.size());
	}
   }
}

Producción:

Tree Set Example!

Tree set data: 12 34 45 63
Tree Set size: 4

First data: 12
Last data: 63

Data is removed from tree set

Now the tree set contain: 12 34 63
Now the size of tree set: 3

Tree Set is empty.

Categorías
Collections

Implementar comparable para un TreeSet

El primer ejemplo a continuación muestra un error común cuando se agrega un objeto a un conjunto. Porque cada elemento de un conjunto debe ser único, cualquier objeto debe compararse con los objetos del conjunto antes de agregarlo.

1. Error común de interfaz comparable

Primero tome una toma en el siguiente código que crea 3 perros y agregue esos perros a un TreeSet.

import java.util.TreeSet;
 
class Dog {
    int size;
    Dog(int s) {
        size = s;
    }
}
 
public class ImpComparableWrong {
 
    public static void main(String[] args) {
        TreeSet<Integer> i = new TreeSet<Integer>();
        TreeSet<Dog> d = new TreeSet<Dog>();
        d.add(new Dog(1));
        d.add(new Dog(2));
        d.add(new Dog(1));
 
        i.add(1);
        i.add(2);
        i.add(3);
 
        System.out.println(d.size() + &quot; &quot; + i.size());
    }
}

La salida es:

correr:

Exception in thread "main" java.lang.ClassCastException: Dog cannot be cast to java.lang.Comparable
        at java.util.TreeMap.put(TreeMap.java:542)
        at java.util.TreeSet.add(TreeSet.java:238)
        at ImpComparableWrong.main(ImpComparableWrong.java:17)
Java Result: 1
BUILD SUCCESSFUL (total time: 2 seconds)

La razón es que Class Dog necesita implementar Comparable para que un TreeSet (que mantiene sus elementos ordenados) pueda contener objetos Dog. El objeto agregado no se puede comparar con los elementos actualmente en el conjunto, la llamada add (Object) arroja una ClassCastException. Para que un objeto sea comparable, la clase definida por el usuario debe implementar la interfaz Comparable.

2. Solución para implementar Comparable para un TreeSet

El siguiente es el código corregido (que implementa Comparable):

import java.util.TreeSet;
 
class Dog implements Comparable<Dog> {
 
    int size;
 
    Dog(int s) {
        size = s;
    }
 
    public int compareTo(Dog o) {
        return size - o.size;
    }
}
 
public class ImpComparable {
 
    public static void main(String[] args) {
 
        TreeSet<Dog> d = new TreeSet<Dog>();
        d.add(new Dog(1));
        d.add(new Dog(2));
        d.add(new Dog(1));
 
        TreeSet<Integer> i = new TreeSet<Integer>();
        i.add(1);
        i.add(2);
        i.add(3);
 
        System.out.println(d.size() + &quot; &quot; + i.size());
    }
}

Producción:

run:
2 3
BUILD SUCCESSFUL (total time: 0 seconds)

3. Comparador frente a comparable

Echa un vistazo a la comparación y averigua cuándo usar cuál.