LinkedList vs. Map

In my coursework, we did a lot of work with LinkedList. So when I had an application where I wanted to keep a list of name-value pairs, I created an object with two members - name and value - and made a LinkedList of them. Everything-looks-like-a-nail syndrome.
Now I've discovered that there are Java classes just for this - HashMap, HashTable, TreeMap etc.
So should I change my code? Or should I stick with the LinkedList? Which of the Map classes would provide the fastest search?

Does it perform OK? Does it bother you emotionallythat you
could have used Maps?Yes, it's working, but it isn't fast enough. I can't
say if that's because I used a LinkedList or not, I
don't know. And yes, I will have trouble sleeping if
I find out that Map would have been a better solution.
: )How "not fast enough" is it?
Switching from a List to a Map should be a fairly easy (depending on how clean your design is), and from what you said about getting by key, Map sounds like the way to go. (You also asked about "searching every element" or something. That sounds like an iteration, not a search, and you can use Map's keySet(), entrySet() or values() method, each of which returns a Collection that can be iterated over. That should perform the same as iterating over a List--or very very close to it.)
Nonetheless, if you're looking for a performance improvement, it would be a good idea to use a profiler to find out where the real bottleneck is. JProfiler, JProbe, and OptimizeIt all have demo versions, I think, or google for java profiler.
Of course, if you've got 20,000 elements, it seems likely that switching from a linear search to a hash-based lookup will make a difference.
I just need the basics. And everybody is searching
the same instance of the object, but nobody is
changing it, so I don't need synchronization. Right?Depends what you mean by "changing it." If you populate the list or map first, and then do your searhc/retrieve operations without any more adds or deletes, then no, you don't need to sync. However, if you have more than one thread accessing your map (or list) and one or more of those threads could me adding to or removing form the map or list (structurally modifying it), then you need synchronization.

Similar Messages

  • Prevent scaling of leaf nodes

    I am trying to implement a simple map solution in JavaFX 2.0. I have map object in a given resolution and some "car" objects (for example Rectangle) that I would like to overlay the map.
    My intention is to create a Group node containing the map objects and the "car" objects. This way I would be able to pan / zoom by only changing the Group transformation. For the map objects this should work fine. For the "car" object, I would like to apply the same transformation to simplify the positioning of the objects. But, the transformation seems to also be used to draw the shape (i.e. effecting the size of the "car").
    I can think of two options:
    1. Apply the inverse transform when drawing the shape
    2. Draw a bit map
    I really just want to be able to draw a simple shape (fixed size in pixels is OK), but at the same time utilise the group transformation for pan / zoom operations. What is the best practice here? If the Rectangle is 20x20 pixels, I would like to offset the Rectangle by 10 pixels to get it centred correctly.
    PS
    I would like to avoid using an image, since I might need to change it dynamically (minor changes like colour, line-width, etc.).
    Edited by: 885374 on Sep 15, 2011 2:35 AM

    Hi Zonski
    Thanks for your suggestions. The scaling hint was realy helpfull. No luck with the StackPane though, since it seemed to scale the map objects in unwanted ways (got hints about that from the API documentation too). For your convenience, I have included a small example illustrating what I came up with. The example compiles on 'javafx_apps-2_0-beta-b42-23_aug_2011' and you may play with the Zoom factor and Pan offsets to observe the effect.
    Please feel free to comment or suggest changes!
    package com.demo.javafx;
    import javafx.application.Application;
    import javafx.scene.Group;
    import javafx.scene.Scene;
    import javafx.scene.paint.Color;
    import javafx.scene.shape.Polygon;
    import javafx.scene.shape.SVGPath;
    import javafx.scene.transform.Scale;
    import javafx.scene.transform.Translate;
    import javafx.stage.Stage;
    import java.util.Collection;
    import java.util.LinkedList;
    * Simple map / track solution demonstrating the use of separate map and track groups to ease pan / zoom operations
    * in the map while maintaining the size of the track objects. Below is a illustration of the scene graph:
    * root (Group)
    *    --> mapLayers (Group)
    *           --> mapLayer1 (Group)
    *                  --> Blue Polygon
    *           --> mapLayer2 (Group)
    *                  --> Green Polygon
    *    --> trackLayer (Group)
    *           --> trackShape (SVGPath)
    * Note!
    * Coordinate (0, 0) is in the center of the window when PAN_OFFSET_X and PAN_OFFSET_Y is zero.
    public class StackPaneDemo extends Application {
        private static final int SCREEN_WIDTH = 600;
        private static final int SCREEN_HEIGHT = 600;
        private static final double ZOOM_FACTOR = 1.0;
        private static final double PAN_OFFSET_X = 0.0;
        private static final double PAN_OFFSET_Y = 0.0;
        @Override
        public void start(final Stage stage) throws Exception {
            Group root = new Group();
            Scene scene = new Scene(root, SCREEN_WIDTH, SCREEN_HEIGHT, Color.BLACK);
            stage.setScene(scene);
            // First map layer
            Group mapLayer1 = new Group();
            mapLayer1.getChildren().addAll(new PolygonShape(Color.BLUE, 0.0, 0.0, -100.0, 0.0, -100.0, -100.0, 0.0, -100.0));
            // Second map layer
            Group mapLayer2 = new Group();
            mapLayer2.getChildren().addAll(new PolygonShape(Color.GREEN, 0.0, 0.0, 100.0, 0.0, 100.0, 100.0, 0.0, 100.0));
            // Create the map group with two map layers
            // 1. The map group is there to be able to pan / zoom all map layers at once (i.e. not each individual layer)
            // 2. Multiple map layers are added to be able to hide map details later (i.e. hide individual layers)
            Group mapLayers = new Group();
            mapLayers.getChildren().addAll(mapLayer1, mapLayer2);
            // Translate and scale the map
            mapLayers.getTransforms().addAll(new Translate(-PAN_OFFSET_X + SCREEN_WIDTH / 2,
                                                           PAN_OFFSET_Y + SCREEN_HEIGHT / 2),
                                             new Scale(ZOOM_FACTOR, ZOOM_FACTOR));
            // Create the a track layer
            Group trackLayer = new Group();
            trackLayer.getChildren().addAll(new TrackShape(0, 0), new TrackShape(100, 100), new TrackShape(200, 200));
            // Translate the track layer
            trackLayer.getTransforms().addAll(new Translate(-PAN_OFFSET_X + SCREEN_WIDTH / 2,
                                                            PAN_OFFSET_Y + SCREEN_HEIGHT / 2));
            // Add the map / track layers to the root node
            root.getChildren().addAll(mapLayers, trackLayer);
            // Show the stage
            stage.show();
         * Simple track representation using SVG Path (need to flip the y-axis)
        private class TrackShape extends SVGPath {
            public TrackShape(final double x, final double y) {
                setTranslateX(x * ZOOM_FACTOR);
                setTranslateY(-y * ZOOM_FACTOR);  // Note: Positive Y should point upwards
                setStroke(Color.WHITE);
                setContent("M0,-10 V10 M-10,0 H10");
         * Simple map object using Polygon (need to flip the y-axis)
        private class PolygonShape extends Polygon {
            public PolygonShape(final Color color, final Double ... points) {
                final Collection<Double> pointsWithFlippedYAxis = new LinkedList<Double>();
                boolean isYCoordinate = false;
                for (Double point : points) {
                    pointsWithFlippedYAxis.add(isYCoordinate ? -point : point);  // Note: Positive Y should point upwards
                    isYCoordinate = !isYCoordinate;
                getPoints().addAll(pointsWithFlippedYAxis);
                setStroke(color);
        public static void main(String[] args) throws InterruptedException {
            launch(args);
    }

  • Wierdness with NIO socket on Solaris 2.10 part I I

    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.nio.channels.spi.SelectorProvider;
    import java.util.*;
    public class NioClient implements Runnable {
    private InetAddress hostAddress;
    private int port;
    private Selector selector;
    private ByteBuffer readBuffer = ByteBuffer.allocate(8192);
    private List pendingChanges = new LinkedList();
    private Map pendingData = new HashMap();
    private Map rspHandlers = Collections.synchronizedMap(new HashMap());
    public NioClient(InetAddress hostAddress, int port) throws IOException {
    this.hostAddress = hostAddress;
    this.port = port;
    this.selector = this.initSelector();
    public void send(byte[] data, RspHandler handler) throws IOException {
    SocketChannel socket = this.initiateConnection();
    this.rspHandlers.put(socket, handler);
    synchronized (this.pendingData) {
    List queue = (List) this.pendingData.get(socket);
    if (queue == null) {
    queue = new ArrayList();
    this.pendingData.put(socket, queue);
    queue.add(ByteBuffer.wrap(data));
    this.selector.wakeup();
    public void run() {
    while (true) {
    try {
    synchronized (this.pendingChanges) {
    Iterator changes = this.pendingChanges.iterator();
    while (changes.hasNext()) {
    ChangeRequest change = (ChangeRequest) changes.next();
    switch (change.type) {
    case ChangeRequest.CHANGEOPS:
    SelectionKey key = change.socket
    .keyFor(this.selector);
    key.interestOps(change.ops);
    break;
    case ChangeRequest.REGISTER:
    change.socket.register(this.selector, change.ops);
    break;
    this.pendingChanges.clear();
    this.selector.select();
    Iterator selectedKeys = this.selector.selectedKeys().iterator();
    while (selectedKeys.hasNext()) {
    SelectionKey key = (SelectionKey) selectedKeys.next();
    selectedKeys.remove();
    if (!key.isValid()) {
    continue;
    if (key.isConnectable()) {
    this.finishConnection(key);
    } else if (key.isReadable()) {
    this.read(key);
    } else if (key.isWritable()) {
    this.write(key);
    } catch (Exception e) {
    e.printStackTrace();
    private void read(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    this.readBuffer.clear();
    int numRead;
    try {
    numRead = socketChannel.read(this.readBuffer);
    } catch (IOException e) {
    key.cancel();
    socketChannel.close();
    return;
    if (numRead == -1) {
    key.channel().close();
    key.cancel();
    return;
    this.handleResponse(socketChannel, this.readBuffer.array(), numRead);
    private void handleResponse(SocketChannel socketChannel, byte[] data,
    int numRead) throws IOException {
    byte[] rspData = new byte[numRead];
    System.arraycopy(data, 0, rspData, 0, numRead);
    RspHandler handler = (RspHandler) this.rspHandlers.get(socketChannel);
    if (handler.handleResponse(rspData)) {
    socketChannel.close();
    socketChannel.keyFor(this.selector).cancel();
    private void write(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    synchronized (this.pendingData) {
    List queue = (List) this.pendingData.get(socketChannel);
    while (!queue.isEmpty()) {
    ByteBuffer buf = (ByteBuffer) queue.get(0);
    socketChannel.write(buf);
    if (buf.remaining() > 0) {
    break;
    queue.remove(0);
    if (queue.isEmpty()) {
    key.interestOps(SelectionKey.OP_READ);
    private void finishConnection(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    try {
    socketChannel.finishConnect();
    } catch (IOException e) {
    System.out.println(e);
    key.cancel();
    return;
    key.interestOps(SelectionKey.OP_WRITE);
    private SocketChannel initiateConnection() throws IOException {
    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
    socketChannel
    .connect(new InetSocketAddress(this.hostAddress, this.port));
    synchronized (this.pendingChanges) {
    this.pendingChanges.add(new ChangeRequest(socketChannel,
    ChangeRequest.REGISTER, SelectionKey.OP_CONNECT));
    return socketChannel;
    private Selector initSelector() throws IOException {
    return SelectorProvider.provider().openSelector();
    public static void main(String[] args) {
    try {
    System.out.println ("the host name is " + args[0]);
    NioClient client = new NioClient(
    InetAddress.getByName(args[0]), 4444);
    Thread t = new Thread(client);
    t.setDaemon(true);
    t.start();
    RspHandler handler = new RspHandler();
    client.send(
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><a><queryInstrument/></a>\n"
    .getBytes(), handler);
    handler.waitForResponse();
    } catch (Exception e) {
    e.printStackTrace();
    }Edited by: LuriRon on Mar 16, 2009 10:42 AM

    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.nio.channels.spi.SelectorProvider;
    import java.util.*;
    public class NioClient implements Runnable {
    private InetAddress hostAddress;
    private int port;
    private Selector selector;
    private ByteBuffer readBuffer = ByteBuffer.allocate(8192);
    private List pendingChanges = new LinkedList();
    private Map pendingData = new HashMap();
    private Map rspHandlers = Collections.synchronizedMap(new HashMap());
    public NioClient(InetAddress hostAddress, int port) throws IOException {
    this.hostAddress = hostAddress;
    this.port = port;
    this.selector = this.initSelector();
    public void send(byte[] data, RspHandler handler) throws IOException {
    SocketChannel socket = this.initiateConnection();
    this.rspHandlers.put(socket, handler);
    synchronized (this.pendingData) {
    List queue = (List) this.pendingData.get(socket);
    if (queue == null) {
    queue = new ArrayList();
    this.pendingData.put(socket, queue);
    queue.add(ByteBuffer.wrap(data));
    this.selector.wakeup();
    public void run() {
    while (true) {
    try {
    synchronized (this.pendingChanges) {
    Iterator changes = this.pendingChanges.iterator();
    while (changes.hasNext()) {
    ChangeRequest change = (ChangeRequest) changes.next();
    switch (change.type) {
    case ChangeRequest.CHANGEOPS:
    SelectionKey key = change.socket
    .keyFor(this.selector);
    key.interestOps(change.ops);
    break;
    case ChangeRequest.REGISTER:
    change.socket.register(this.selector, change.ops);
    break;
    this.pendingChanges.clear();
    this.selector.select();
    Iterator selectedKeys = this.selector.selectedKeys().iterator();
    while (selectedKeys.hasNext()) {
    SelectionKey key = (SelectionKey) selectedKeys.next();
    selectedKeys.remove();
    if (!key.isValid()) {
    continue;
    if (key.isConnectable()) {
    this.finishConnection(key);
    } else if (key.isReadable()) {
    this.read(key);
    } else if (key.isWritable()) {
    this.write(key);
    } catch (Exception e) {
    e.printStackTrace();
    private void read(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    this.readBuffer.clear();
    int numRead;
    try {
    numRead = socketChannel.read(this.readBuffer);
    } catch (IOException e) {
    key.cancel();
    socketChannel.close();
    return;
    if (numRead == -1) {
    key.channel().close();
    key.cancel();
    return;
    this.handleResponse(socketChannel, this.readBuffer.array(), numRead);
    private void handleResponse(SocketChannel socketChannel, byte[] data,
    int numRead) throws IOException {
    byte[] rspData = new byte[numRead];
    System.arraycopy(data, 0, rspData, 0, numRead);
    RspHandler handler = (RspHandler) this.rspHandlers.get(socketChannel);
    if (handler.handleResponse(rspData)) {
    socketChannel.close();
    socketChannel.keyFor(this.selector).cancel();
    private void write(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    synchronized (this.pendingData) {
    List queue = (List) this.pendingData.get(socketChannel);
    while (!queue.isEmpty()) {
    ByteBuffer buf = (ByteBuffer) queue.get(0);
    socketChannel.write(buf);
    if (buf.remaining() > 0) {
    break;
    queue.remove(0);
    if (queue.isEmpty()) {
    key.interestOps(SelectionKey.OP_READ);
    private void finishConnection(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    try {
    socketChannel.finishConnect();
    } catch (IOException e) {
    System.out.println(e);
    key.cancel();
    return;
    key.interestOps(SelectionKey.OP_WRITE);
    private SocketChannel initiateConnection() throws IOException {
    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
    socketChannel
    .connect(new InetSocketAddress(this.hostAddress, this.port));
    synchronized (this.pendingChanges) {
    this.pendingChanges.add(new ChangeRequest(socketChannel,
    ChangeRequest.REGISTER, SelectionKey.OP_CONNECT));
    return socketChannel;
    private Selector initSelector() throws IOException {
    return SelectorProvider.provider().openSelector();
    public static void main(String[] args) {
    try {
    System.out.println ("the host name is " + args[0]);
    NioClient client = new NioClient(
    InetAddress.getByName(args[0]), 4444);
    Thread t = new Thread(client);
    t.setDaemon(true);
    t.start();
    RspHandler handler = new RspHandler();
    client.send(
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><a><queryInstrument/></a>\n"
    .getBytes(), handler);
    handler.waitForResponse();
    } catch (Exception e) {
    e.printStackTrace();
    }Edited by: LuriRon on Mar 16, 2009 10:42 AM

  • Wierdness with NIO socket on Solaris 2.10 part I

    i tried the following NioClient and MockServer, and saw some weird behavior.
    1. If i run both the client and server on the same machine on Windows, the client connects to the server, queries the instrument and gets the list of instruments back.
    2. if i run both client and server on the same Solaris 2.10 box, the NioClient doesn't get anything back from the MockServer, not even an ACCEPT
    3. if i run the client and the server on different solaris 2.10 machines, they work fine.
    have anyone seen this before? can sometone sheds some lights?
    import java.net.*;
    import java.io.*;
    public class MockServer
         public static int counter = 2;
        public static void main(String[] args) throws IOException {
             int portNumber = Integer.parseInt(args[0]);
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(portNumber);
            } catch (IOException e) {
                System.err.println("Could not listen on port: " + portNumber);
                System.exit(1);
             System.out.println ("Listening on socket " + portNumber);
            do {             
                 Socket clientSocket = null;
                 try {
                     clientSocket = serverSocket.accept();
                     System.out.println ("starting a new client....");
                     MyThread mt = new MyThread (clientSocket);
                     mt.run ();
                 } catch (IOException e) {
                     System.err.println("Accept failed.");
                     System.exit(1);
            while (true);
    class MyThread
         private final Socket clientSocket;
         MyThread (Socket clientSocket)
              this.clientSocket = clientSocket;
         public void run ()
            new Thread (new Runnable () {
                     public void run ()
                          try
                               boolean instrumentquery = false;
                               PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
                               BufferedReader in = new BufferedReader(
                                           new InputStreamReader(
                                           clientSocket.getInputStream()));
                               String inputLine;                          
                               String successoutputLine =
                                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><return><returncode>success</returncode><detail>everything is good</detail></return>";
                               String failoutputLine =
                                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><return><returncode>failure</returncode><detail>something is not good</detail></return>";
                               String instrumentsoutput =
                                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><instruments><instrument><contract>usg-505Y</contract><cusip>12131121</cusip><deactivated>false</deactivated><halted>false</halted></instrument><instrument><contract>usg-305Y</contract><cusip>121312342</cusip><deactivated>false</deactivated><halted>false</halted></instrument></instruments>";
                               while ((inputLine = in.readLine()) != null) {
                                    System.out.println ("Receiving the following" + inputLine);
                                    if (inputLine.contains("queryInstrument")) instrumentquery = true;
                                    if (inputLine.contains("</a>"))
                                         if (instrumentquery)
                                              instrumentquery = false;
                                              System.out.println ("Sending " + instrumentsoutput);
                                              out.println (instrumentsoutput);
                                         else
                                              if ((MockServer.counter % 2) == 0)
                                                   System.out.println ("Sending " + successoutputLine);
                                                   out.println(successoutputLine);
                                              else
                                                   System.out.println ("Sending " + failoutputLine);
                                                   out.println(failoutputLine);
                                              MockServer.counter++;
                               out.close();
                               in.close();
                               clientSocket.close();}
                          catch (Exception ex)
                 }).start (); }
    }please see topic "wierdness with NIO socket on Solaris 2.10 part II" for the NioClient code as the maximum per topic is 5000.

    code for NioClient.java
    import java.io.IOException;
    import java.net.InetAddress;
    import java.net.InetSocketAddress;
    import java.net.Socket;
    import java.nio.ByteBuffer;
    import java.nio.channels.SelectionKey;
    import java.nio.channels.Selector;
    import java.nio.channels.SocketChannel;
    import java.nio.channels.spi.SelectorProvider;
    import java.util.*;
    public class NioClient implements Runnable {
    private InetAddress hostAddress;
    private int port;
    private Selector selector;
    private ByteBuffer readBuffer = ByteBuffer.allocate(8192);
    private List pendingChanges = new LinkedList();
    private Map pendingData = new HashMap();
    private Map rspHandlers = Collections.synchronizedMap(new HashMap());
    public NioClient(InetAddress hostAddress, int port) throws IOException {
    this.hostAddress = hostAddress;
    this.port = port;
    this.selector = this.initSelector();
    public void send(byte[] data, RspHandler handler) throws IOException {
    SocketChannel socket = this.initiateConnection();
    this.rspHandlers.put(socket, handler);
    synchronized (this.pendingData) {
    List queue = (List) this.pendingData.get(socket);
    if (queue == null) {
    queue = new ArrayList();
    this.pendingData.put(socket, queue);
    queue.add(ByteBuffer.wrap(data));
    this.selector.wakeup();
    public void run() {
    while (true) {
    try {
    synchronized (this.pendingChanges) {
    Iterator changes = this.pendingChanges.iterator();
    while (changes.hasNext()) {
    ChangeRequest change = (ChangeRequest) changes.next();
    switch (change.type) {
    case ChangeRequest.CHANGEOPS:
    SelectionKey key = change.socket
    .keyFor(this.selector);
    key.interestOps(change.ops);
    break;
    case ChangeRequest.REGISTER:
    change.socket.register(this.selector, change.ops);
    break;
    this.pendingChanges.clear();
    this.selector.select();
    Iterator selectedKeys = this.selector.selectedKeys().iterator();
    while (selectedKeys.hasNext()) {
    SelectionKey key = (SelectionKey) selectedKeys.next();
    selectedKeys.remove();
    if (!key.isValid()) {
    continue;
    if (key.isConnectable()) {
    this.finishConnection(key);
    } else if (key.isReadable()) {
    this.read(key);
    } else if (key.isWritable()) {
    this.write(key);
    } catch (Exception e) {
    e.printStackTrace();
    private void read(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    this.readBuffer.clear();
    int numRead;
    try {
    numRead = socketChannel.read(this.readBuffer);
    } catch (IOException e) {
    key.cancel();
    socketChannel.close();
    return;
    if (numRead == -1) {
    key.channel().close();
    key.cancel();
    return;
    this.handleResponse(socketChannel, this.readBuffer.array(), numRead);
    private void handleResponse(SocketChannel socketChannel, byte[] data,
    int numRead) throws IOException {
    byte[] rspData = new byte[numRead];
    System.arraycopy(data, 0, rspData, 0, numRead);
    RspHandler handler = (RspHandler) this.rspHandlers.get(socketChannel);
    if (handler.handleResponse(rspData)) {
    socketChannel.close();
    socketChannel.keyFor(this.selector).cancel();
    private void write(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    synchronized (this.pendingData) {
    List queue = (List) this.pendingData.get(socketChannel);
    while (!queue.isEmpty()) {
    ByteBuffer buf = (ByteBuffer) queue.get(0);
    socketChannel.write(buf);
    if (buf.remaining() > 0) {
    break;
    queue.remove(0);
    if (queue.isEmpty()) {
    key.interestOps(SelectionKey.OP_READ);
    private void finishConnection(SelectionKey key) throws IOException {
    SocketChannel socketChannel = (SocketChannel) key.channel();
    try {
    socketChannel.finishConnect();
    } catch (IOException e) {
    System.out.println(e);
    key.cancel();
    return;
    key.interestOps(SelectionKey.OP_WRITE);
    private SocketChannel initiateConnection() throws IOException {
    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
    socketChannel
    .connect(new InetSocketAddress(this.hostAddress, this.port));
    synchronized (this.pendingChanges) {
    this.pendingChanges.add(new ChangeRequest(socketChannel,
    ChangeRequest.REGISTER, SelectionKey.OP_CONNECT));
    return socketChannel;
    private Selector initSelector() throws IOException {
    return SelectorProvider.provider().openSelector();
    public static void main(String[] args) {
    try {
    System.out.println ("the host name is " + args[0]);
    NioClient client = new NioClient(
    InetAddress.getByName(args[0]), 4444);
    Thread t = new Thread(client);
    t.setDaemon(true);
    t.start();
    RspHandler handler = new RspHandler();
    client.send(
    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><a><queryInstrument/></a>\n"
    .getBytes(), handler);
    handler.waitForResponse();
    } catch (Exception e) {
    e.printStackTrace();
    }

  • How to print the content of LinkedList int[] and LinkedList LinkedList ?

    Hi guys, its been a long time since i posted here, and now im coming back to programming using java. My problem is, how can i print the content of the list?
    Example:
    LinkedList<int[]> list = new LinkedList<int[]>;
    int[] input = {1,2,3,4,5};
    int[] input2 = {2,32,43,54,65};
    list.add(input);
    list.add(input2);
    how can i print all the content of the linkedlist?
    Please help me..I know its a dumb question but i really dunno how.
    here is the code:
    import java.util.LinkedList;
    import java.util.Scanner;
    import java.util.Arrays;
    public class Test{
         static void printThis(String[] in){
              System.out.print("Value: ");
              for(int i = 0;i<in.length;i++){
                   System.out.print(in[i] + " ");
              System.out.println();
         static void reset(String[] val){
              for(int i = 0;i<val.length;i++){
                   val[i] = "";
         public static void main(String[] args){
              LinkedList<String[]> list = new LinkedList<String[]>();
              LinkedList<String> listTrans = new LinkedList<String>();
              System.out.print("Enter the number of records: ");
              Scanner s = new Scanner(System.in);
              int numOfRecords = s.nextInt();
              System.out.print("Enter the number of records per run: ");
              s = new Scanner(System.in);
              System.out.println();
              int numOfRecordsInMemory = s.nextInt();
              String[] getData = new String[numOfRecords];
              String[] transferData = new String[numOfRecordsInMemory];
              int numOfRuns = 0;
              int counter = 0;
              for(int i = 0;i<numOfRecords;i++){
                   counter++;
                   System.out.print("Enter value number " + counter + ": ");
                   Scanner scan = new Scanner(System.in);
                   getData[i] = scan.next();
                   listTrans.add(getData);
              if(getData.length%numOfRecordsInMemory == 0){
                   numOfRuns = getData.length/numOfRecordsInMemory;
              }else if(getData.length%numOfRecordsInMemory != 0){
                   numOfRuns =(int)(getData.length/numOfRecordsInMemory)+ 1;
              System.out.println();
              System.out.println("Number of Runs: " + numOfRuns);
         int pass = 0;
         System.out.println("Size of the main list: " + listTrans.size());
         while(listTrans.size() != 0){
              if(listTrans.size() >= numOfRecordsInMemory){
                   for(int i = 0;i<numOfRecordsInMemory;i++){
                        transferData[i] = listTrans.remove();
                   System.out.println("Size of the list: " + listTrans.size());
                   printThis(transferData);
                   System.out.println();
                   Arrays.sort(transferData);
                   list.add(transferData);
                   reset(transferData);
              }else if(listTrans.size() < numOfRecordsInMemory){
                   pass = listTrans.size();
                   for(int k = 0;k<pass;k++){
                        transferData[k] = listTrans.remove();
                   System.out.println("Size of the list: " + listTrans.size());
                   printThis(transferData);
                   System.out.println();
                   Arrays.sort(transferData);
                   list.add(transferData);
                   reset(transferData);
    //This is the part that is confusing me.
    //im trying to print it but its not working.
              System.out.println("Size of the next list: " + list.size());
    //          for(int i = 0;i<list.size();i++){
    //                    System.out.println();
    //               for(int j = 0;j<list.get(i)[j].length();j++){                    
    //                    System.out.print(list.get(i)[j] + " ");

    Here's the funnest, mabye clearest way you could do it: Use 2 Mappers
    package tjacobs.util;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import tjacobs.Arrays;
    public class Mapper <T>{
         public static interface MappedFunc<T> {
              void map(T value);
         public Mapper(T[] vals, MappedFunc<T> function) {
              this (new Arrays.ArrayIterator<T>(vals), function);
         public Mapper(Iterator<T> iterator, MappedFunc<T> function) {
              while (iterator.hasNext()) {
                   function.map(iterator.next());
         public static void main(String[] args) {
              String[] s = new String[] {"a","b", "c", "abc", "ab"};
              MappedFunc<String> func = new MappedFunc<String>() {
                   public void map(String s) {
                        if (s.toLowerCase().startsWith("a")) {
                             System.out.println(s);
              Mapper m = new Mapper(s, func);
    }

  • How to keep the original sequence of a map

    I want the equivalent of a Hashtable or Map class (I need keys and corresponding objects) which, once fully populated, will guarantee to get the key/object pairs back out using the order in which they were added, rather than by sort order of the keys.
    ( The bigger objective is to compare two such collections, A and B, to see which key/object pairs exist in A but not B, and which exist in B but not A. However, for presentation purposes, I need to keep the original order in which everything was read.)
    What's the most efficient way to do this ? I'm sure I've missed something really simplistic but, hey, it's Monday......

    There is no way to retrieve objects from any map in the order they were incerted unless you add some logic to the way you are incering it.
    Here is an example of such logic, where I want to retrieve "states" in the same order as I put them:
         public static void main(String[] args){
              HashMap map = new HashMap();
              map.put("1" + "PA", "Pensylvania");
              map.put("2" + "NJ", "New Jersey");
              map.put("3" + "CA", "California");
              map.put("4" + "TX", "Texas");
              LinkedList ls = new LinkedList(map.keySet());
              Collections.sort(ls);
              Iterator iter = ls.iterator();
             String stAbbrv = null;
              while (iter.hasNext()){
                   stAbbrv = (String)iter.next();
                   System.out.println(stAbbrv.substring(1) + " - " + map.get(stAbbrv));
         }the output is:
    PA - Pensylvania
    NJ - New Jersey
    CA - California
    TX - TexasHope it helps
    Alex
    [email protected]

  • JPA One-To-Many Parent-Child Mapping Problem

    I am trying to map an existing legacy Oracle schema that involves a base class table and two subclass tables that are related by a one-to-many relationship which is of a parent-child nature.
    The following exception is generated. Can anybody provide a suggestion to fix the problem?
    Exception [EclipseLink-45] (Eclipse Persistence Services - 2.0.0.v20091127-r5931): org.eclipse.persistence.exceptions.DescriptorException
    Exception Description: Missing mapping for field [BASE_OBJECT.SAMPLE_ID].
    Descriptor: RelationalDescriptor(domain.example.entity.Sample --> [DatabaseTable(BASE_OBJECT), DatabaseTable(SAMPLE)])
    The schema is as follows:
    CREATE TABLE BASE_OBJECT(
    "BASE_OBJECT_ID" INTEGER PRIMARY KEY NOT NULL,
    "NAME" VARCHAR2(128) NOT NULL,
    "DESCRIPTION" CLOB NOT NULL,
    "BASE_OBJECT_KIND" NUMBER(5,0) NOT NULL );
    CREATE TABLE SAMPLE(
    "SAMPLE_ID" INTEGER PRIMARY KEY NOT NULL,
    "SAMPLE_TEXT" VARCHAR2(128) NOT NULL )
    CREATE TABLE SAMPLE_ITEM(
    "SAMPLE_ITEM_ID" INTEGER PRIMARY KEY NOT NULL,
    "SAMPLE_ID" INTEGER NOT NULL,
    "QUANTITY" INTEGER NOT NULL )
    The entities are related as follows:
    SAMPLE.SAMPLE_ID -> BASE_OBJECT.BASE_OBJECT_ID - The PKs that are used to join the sample to the base class
    SAMPLE_ITEM.SAMPLE_ITEM_ID -> BASE_OBJECT.BASE_OBJECT_ID - The PKs that are used to join the sample item to the base class
    SAMPLE_ITEM.SAMPLE_ID -> SAMPLE.SAMPLE_ID - The FK that is used to join the sample item to the sample class as a child of the parent.
    SAMPLE is one to many SAMPLE_ITEM
    The entity classes are as follows:
    @Entity
    @Table( name = "BASE_OBJECT" )
    @Inheritance( strategy = InheritanceType.JOINED )
    @DiscriminatorColumn( name = "BASE_KIND", discriminatorType = DiscriminatorType.INTEGER )
    @DiscriminatorValue( "1" )
    public class BaseObject
    extends SoaEntity
    @Id
    @GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "BaseObjectIdSeqGen" )
    @SequenceGenerator( name = "BaseObjectIdSeqGen", sequenceName = "BASE_OBJECT_PK_SEQ", allocationSize = 1 )
    @Column( name = "BASE_ID" )
    private long baseObjectId = 0;
    @Entity
    @Table( name = "SAMPLE" )
    @PrimaryKeyJoinColumn( name = "SAMPLE_ID" )
    @AttributeOverride(name="baseObjectId", column=@Column(name="SAMPLE_ID"))
    @DiscriminatorValue( "2" )
    public class Sample
    extends BaseObject
    @OneToMany( cascade = CascadeType.ALL )
    @JoinColumn(name="SAMPLE_ID",referencedColumnName="SAMPLE_ID")
    private List<SampleItem> sampleItem = new LinkedList<SampleItem>();
    @Entity
    @Table( name = "SAMPLE_ITEM" )
    @PrimaryKeyJoinColumn( name = "SAMPLE_ITEM_ID" )
    @AttributeOverride(name="baseObjectId", column=@Column(name="SAMPLE_ITEM_ID"))
    @DiscriminatorValue( "3" )
    public class SampleItem
    extends BaseObject
    @Basic( optional = false )
    @Column( name = "SAMPLE_ID" )
    private long sampleId = 0;
    Edited by: Chris-R on Mar 2, 2010 4:45 PM

    Thanks for the thoroughness. There was a mistake in moving the code over for the forum. The field names are correct throughout the original source code.
    BASE_OBJECT_ID is used throughout.
    I suspect the problem lies in the one-to-many sampleItem(s) relationship that is based upon the subclassed item class. (The relationship is actually "sampleItems" in the real code and somehow got changed in the move over.)
    The problem may lie in the mapping of the attribute override in the child class to the referencing of the item class from the parent side of the relationship in the Sample class.
    I further suspect this may be specific to Eclipselink based upon other postings I've seen on the web that have similar problems...
    Any thoughts?
    Edited by: Chris-R on Mar 3, 2010 9:56 AM

  • Mapping Problem using hibernate and annotations

    Hi,
    i am German student and new to hibernate. I established a mn conetction between to entities using hbm.xml mapping files. now I try to create the same connection applying annotations. unfortunately it does not work and I do not now why. First my error message followed by my classes and xml's:
    Initial SessionFactory creation failed.org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: domain.Termin.person in domain.Person.termine
    Exception in thread "main" java.lang.ExceptionInInitializerError
    at services.HibernateUtil.sessionFactory(HibernateUtil.java:39)
    at services.HibernateUtil.getSessionFactory(HibernateUtil.java:20)
    at test.Test.main(Test.java:20)
    Caused by: org.hibernate.AnnotationException: mappedBy reference an unknown target entity property: domain.Termin.person in domain.Person.termine
    at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:552)
    at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:517)
    at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:43)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1130)
    at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:316)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1286)
    at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:915)
    at services.HibernateUtil.sessionFactory(HibernateUtil.java:36)
    ... 2 more
    package domain;
    import java.util.LinkedList;
    import java.util.List;
    import domain.Termin;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.ManyToMany;
    import javax.persistence.Table;
    @Entity
    @Table(name = "PERSON")
    public class Person {
       private long id;
       private String vorname;
       private String nachname;
       private List<Termin> termine=new LinkedList<Termin>();
       public Person() {
       @Id @GeneratedValue(strategy=GenerationType.AUTO)
       public long getId() {
          return id;
       public void setId(long id) {
          this.id = id;
       public String getNachname() {
          return nachname;
       public void setNachname(String nachname) {
          this.nachname = nachname;
       public String getVorname() {
          return vorname;
       public void setVorname(String vorname) {
          this.vorname = vorname;
       public void addTermin(Termin termin){
          termine.add(termin);
       @ManyToMany(mappedBy="person")
       public List<Termin> getTermine() {
          return termine;
       public void setTermine(List<Termin> termine) {
          this.termine = termine;
    package domain;
    import java.util.ArrayList;
    import java.util.List;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.ManyToMany;
    import javax.persistence.Table;
    @Entity
    @Table(name = "TERMIN")
    public class Termin {
       private long id;
       private String titel;
       private Person eigentuemer;
       private List<Person> teilnehmer= new ArrayList<Person>();
       public void addTeilnehmer(Person person){
          teilnehmer.add(person);
       @ManyToMany
       public List<Person> getTeilnehmer() {
          return teilnehmer;
       public void setTeilnehmer(List<Person> teilnehmer) {
          this.teilnehmer = teilnehmer;
       public Termin() {
       @Id @GeneratedValue(strategy=GenerationType.AUTO)
       public long getId() {
          return id;
       public void setId(long id) {
          this.id = id;
       public String getTitel() {
          return titel;
       public void setTitel(String titel) {
          this.titel = titel;
       public Person getEigentuemer() {
          return eigentuemer;
       public void setEigentuemer(Person eigentuemer) {
          this.eigentuemer = eigentuemer;
    package test;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.Transaction;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.tool.hbm2ddl.SchemaExport;
    import services.HibernateUtil;
    import domain.Person;
    import domain.Termin;
    public class Test {
       public static void main(String[] args) {
          Session session = null;
          HibernateUtil.setRecreateDB(true);
          session = HibernateUtil.getSessionFactory().getCurrentSession();
          /*      Person person1 =new Person();
          person1.setNachname("P1");
          Transaction transaction = session.beginTransaction();
          session.save(person1);
          transaction.commit();
          Person person2 =new Person();
          person2.setNachname("P2");
          session = HibernateUtil.getSessionFactory().getCurrentSession();
          transaction = session.beginTransaction();
          session.save(person2);
          transaction.commit();
          Termin termin1 =new Termin();
          termin1.setTitel("T1");
          termin1.setEigentuemer(person1);
          termin1.addTeilnehmer(person1);
          termin1.addTeilnehmer(person2);
          session = HibernateUtil.getSessionFactory().getCurrentSession();
          transaction = session.beginTransaction();
          session.save(termin1);
          transaction.commit();
       Termin termin2 =new Termin();
          termin2.setTitel("t2");
          termin2.setEigentuemer(person1);
          termin2.addTeilnehmer(person1);
          termin2.addTeilnehmer(person2);
          transaction = session.beginTransaction();
          session.save(termin2);
          transaction.commit();
          session.close();
    package services;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.AnnotationConfiguration;
    import domain.Person;
    import domain.Termin;
    public class HibernateUtil {
       private static boolean recreateDB = false;
       public static void setRecreateDB(boolean recreateDB) {
          HibernateUtil.recreateDB = recreateDB;
       public static SessionFactory getSessionFactory() {
          if (sessionFactory == null) {
             sessionFactory = sessionFactory("hibernate.cfg.xml");
          return sessionFactory;
       private static SessionFactory sessionFactory = null;
       private static SessionFactory sessionFactory(String configurationFileName) {
          try {
             AnnotationConfiguration annotationConfiguration =
                new AnnotationConfiguration()
                .addAnnotatedClass(Person.class)
                .addAnnotatedClass(Termin.class);
             if (recreateDB) annotationConfiguration.setProperty("hibernate.hbm2ddl.auto", "create");
             annotationConfiguration.configure();
             return annotationConfiguration.buildSessionFactory();
          } catch (Throwable ex){
             System.err.println("Initial SessionFactory creation failed." + ex);
             throw new ExceptionInInitializerError(ex);
    <?xml version="1.0" encoding="utf-8"?>
    <!DOCTYPE hibernate-configuration
        PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
        <session-factory >
          <property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
            <property name="hibernate.connection.password">application</property>
            <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
            <property name="hibernate.connection.username">application</property>
            <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
           <property name="current_session_context_class">thread</property>
          <property name="hibernate.show_sql">true</property>
        </session-factory>
    </hibernate-configuration>

    The error message is pretty much telling you the problem:
    mappedBy reference an unknown target entity property: domain.Termin.person in domain.Person.termine
    This tells you that there's a mappedBy setting on the Person class's termine property annotation, and that the property it's referring to (the person property of the Termin class) doesn't exist.
    @ManyToMany(mappedBy="person")
    public List<Termin> getTermine() {
       return termine;
    }If we have a look at the Termin class, indeed it has the following properties:
    id
    teilnehmer
    titel
    eigentuemerAnd no person property. Remember, a property is defined by the existence of a get/set pair for the name. It's unrelated to the types returned by them and the private variables implementing them.
    mappedBy has the equivalent effect to the inverse property in a hbm.xml mapping file - it defines which entity's property will cause the foreign key value to be updated (persisting the relationship to the database). From the context of your code, I'm guessing you really want the annotation to read:
    @ManyToMany(mappedBy="teilnehmer")

  • Sort(java.util.LinkedList java.lang.Object ) doesn't work

    Why doesn't this work?
    LinkedList<Object> sysPropsKeys = new LinkedList<Object>(System.getProperties().keySet());
    Collections.sort(sysPropsKeys);
    cannot fnd symbol
    symbol : method sort(java.util.LinkedList<java.lang.Object>)
    location: class java.util.Collections

    I will admit to not having Java1.5 installed on my machine. Haven't yet had the chance to play with generics, but the above DOES work in 1.4, and SHOULD work in 1.5
    Maybe I'm naive but, System.getProperties() returns a Properties object right?
    According to the API: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Properties.html: Each key and its corresponding value in the property list is a string.
    All the keys SHOULD be strings.
    AFAIK string are comparable, and shouldn't throw class cast exceptions
    Thus the keys returned from getProperties SHOULD be comparable, and compatible for comparision.
    Ok, I can see your point in that some hackers abuse the Properties class by putting non string keys/values into the Properties Map. In that case the code would become more like your above. I'd probably still go with a TreeMap though, rather than a sorted list of keys. Most time you want the keys, you want the values as well. So if the intention is to print out a sorted list of system properties, and their values, keeping it in a map is best.
    Just my 2 cents,
    evnafets

  • ? with a Vector of LinkedLists

    Hi,
    I would like to create a Vector. Each element will be a LinkedList. Each element in my LinkedList will be an Object, call it o. Obejcts like o have a member field called time, which is a BigDecimal. I am doing this because I want each LinkedList to contain o's with the same time value. So if I index into the Vector at 0 I will get a linked list that has Objects of type o and all those objects have time value t0. If I index into the Vector at position x, I will get a LinkedList of objects having time value tx.
    Now, initially my Vector just contained the Objects of type o, so my class just had a method called compareTo() that would provide a natural ordering. This allowed me to do a Collections.binarySearch() when I wanted to insert into the vector.
    Currently I am a little confused as to how and where I will write the new compareTo() method. Basically I have a method that accepts objects of type o and what I want it to do would be to look at o's time field, then do Collections.binarySearch() on the Vector to find the index of the appropriate LinkedList. Then I will just insert into the LinkedList. But I see that the LinkedList class does not have it's own compareTo() method. If I were to write one I would have it simply call the compareTo() method on the first element in it's list.
    Thanks,
    Jeff

    Oh, ok. So you are basically implying that since my
    times will be arbitrary then my binarySearch into the
    Vector will cost more than just inserting a new
    LinkedList into a HashMap (or getting the already
    existing linked list from the HashMap). Makes sense.
    Thanks.Not necessarily that it will be computationally more expensive, just that the vector is a poorer representation of your intent. A Vector (actually, ArrayList would be better) or Array is useful for random access when you know the index. If you want a lookup by an arbitrary key, however, a Map is a more direct realization of your design.
    Under the covers, the Map could very well do a binary search on a List or array anyway, but your code shouldn't know or care about that detail. Your code should just say, as simply and directly as possible, "Give me the elemnts that have a time value of X". map.get(X) is a clean way to do that. Anybody reading the code later (including you, after you've forgotten WTF you were doing) will find that easier to understand than a binary search through a vector to find the list element whose first entry have time value X.

  • How to use Multimaps (Map String, ArrayList String )

    I was using an array to store player names, userIDs, uniqueIDs, and frag counts, but after reading about multimaps in the tutorials, it seems that would be much more efficient. However, I guess I don't quite understand it. Here's how I wanted things stored in my string array:
    String[] connectedUsers = {"user1_name", "user1_userid", "user1_uniqueid", "user1_frags"
                                            "user2_name"...}and here is how I'm attempting to setup and use the 'multimap':
    public class Main {
        static Map<String, ArrayList<String>> connectedUsers;
        public void updatePlayers(String name, String status) {
            String[] statusSplit = status.split(" ");
            if (connectedUsers.containsKey(name)) {
                connectedUsers.put(name, statusSplit[0]);
            else {
                connectedUsers.put(name, statusSplit[0]);
        }It's quite obvious I don't understand how this works, but should I even set this multimap up this way? Perhaps I should use a regular map with a string array for the values?

    You're cool MrOldie. Its just that alarm bells start ringing in my head when people come on and post as much as you do.
    * Created on Jul 28, 2005 by @author Tom Jacobs
    package tjacobs;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.LinkedList;
    import java.util.Map;
    import java.util.Set;
    import java.util.TreeSet;
    * ManyMap is a map that allows more than one value to be stored with any key
    * <p>
    * There are a number of methods in the class that have been deprecated because
    * the original functionality of Map has been violated to accomodate the concept
    * of the ManyMap
    public class ManyMap<T, T2> implements Map<T, T2> {
         private HashMap<T, ArrayList<T2>> mInnerMap;
         public ManyMap() {
              mInnerMap = new HashMap<T, ArrayList<T2>>();
          * @deprecated
         public T2 get(Object obj) {
              ArrayList<T2> ar = _get(obj);
              if (ar == null || ar.size() == 0) {
                   return null;
              return ar.get(0);
         public Iterator<T2> getAll(Object obj) {
              ArrayList<T2> ar = _get(obj);
              if (ar == null || ar.size() == 0) {
                   return null;
              return ar.iterator();          
         public T2 put(T obj1, T2 obj2) {
              ArrayList<T2> ar = _getNotNull(obj1);
              ar.add(obj2);
              return obj2;
         public Set<Map.Entry<T, T2>> entrySet() {
              TreeSet<Map.Entry<T, T2>> entries = new TreeSet<Map.Entry<T, T2>>();
              Iterator<T> _i = mInnerMap.keySet().iterator();
              while (_i.hasNext()) {
                   T key = _i.next();
                   Iterator<T2> vals = mInnerMap.get(key).iterator();
                   while (vals.hasNext()) {
                        Entry<T, T2> entry = new Entry<T, T2>(key, vals.next());
                        entries.add(entry);
              return entries;
         public int size() {
              return mInnerMap.size();
         public int valuesSize() {
              int vals = 0;
              Iterator<T> _i = mInnerMap.keySet().iterator();
              while (_i.hasNext()) {
                   T key = _i.next();
                   ArrayList<T2> ar = mInnerMap.get(key);
                   vals += ar.size();
              return vals;
         public void clear() {
              mInnerMap.clear();
         public void putAll(Map<? extends T, ? extends T2> map) {
              Iterator _i = map.entrySet().iterator();
              while(_i.hasNext()) {
                   Map.Entry<? extends T, ? extends T2> entry = (Map.Entry<? extends T, ? extends T2>) _i.next();
                   put(entry.getKey(), entry.getValue());
         public Collection <T2> values() {
              LinkedList ll = new LinkedList();
              Iterator<ArrayList<T2>> _i = mInnerMap.values().iterator();
              while (_i.hasNext()) {
                   ll.addAll(_i.next());
              return ll;
         public boolean containsValue(Object val) {
              Iterator<ArrayList<T2>> values = mInnerMap.values().iterator();
              while (values.hasNext()) {
                   if (values.next().contains(val)) return true;
              return false;
         public boolean containsKey(Object key) {
              return mInnerMap.containsKey(key);
         public T2 remove(Object obj) {
              Iterator<ArrayList<T2>> values = mInnerMap.values().iterator();
              boolean found = false;
              while (values.hasNext()) {
                   if (values.next().remove(obj)) {
                        found = true;
              return found ? (T2)obj : null;
         public boolean isEmpty() {
              return valuesSize() == 0;
         @SuppressWarnings("hiding")
         private class Entry<T, T2> implements Map.Entry<T, T2> {
              T key;
              T2 val;
              public Entry (T obj1, T2 obj2) {
                   key = obj1;
                   val = obj2;
              public T2 getValue() {
                   return val;
              public T getKey() {
                   return key;
              public T2 setValue(T2 obj) {
                   return val = obj;
         public Set<T> keySet() {
              return mInnerMap.keySet();
         public ArrayList<T2> _get (Object obj) {
              return mInnerMap.get(obj);
         public ArrayList<T2> _getNotNull (T obj) {
              ArrayList<T2> list = _get(obj);
              if (list == null) {
                   list = new ArrayList<T2>(1);
                   mInnerMap.put(obj, list);
              return list;
    }Edited by: tjacobs01 on Aug 19, 2008 12:28 PM

  • Problem with fetching Map object from ObjectInputStream

    Hi, please can you help me with the following...I've never seen this before (with my limited experience of JDK1.5)
    ObjectInputStream is = new ObjectInputStream(new FileInputStream(store));
    Map<Integer, Report> readObject = (Map<Integer, Report>) is.readObject();This code gives me a warning...
    Type safety: The cast from Object to Map<Integer,Report> is actually checking against the erased type Map
    How can I get rid of this warning?

         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream( baos );
         List<String> list = new LinkedList<String>();
         list.add( "one" );
         list.add( "two" );
         oos.writeObject( list );
         oos.flush(); oos.close();
         ObjectInputStream ois = new ObjectInputStream
             ( new ByteArrayInputStream( baos.toByteArray() ) );
         List<String> list2 = (List<String>)ois.readObject();Give me 1 compile time error (Test.java:109: warning: [unchecked] unchecked cast), and no runtime errors.
    Removing the <String> from "list" add some more [uncheked], but still runs fine (no runtime warning). Adding a none-String only causes a problem when I try to "get" it. (class cast).
    When do you get this warning?

  • LinkedList parameter problem

    I created a web services application a few months ago and I am now trying to add a new method that contains a LinkedList as an input parameter. I used the weblogic.webservice.clientgen command to create the needed Codec and Holder classes for a string array when I first created this application and now I am trying to do the same for a LinkedList. However when I run my code to call the web service I get the following NullPointerException:
    java.lang.NullPointerException
         at weblogic.xml.schema.binding.TypedSoapArrayCodecBase.serializeMultiDimArray(TypedSoapArrayCodecBase.java:145)
         at weblogic.xml.schema.binding.SoapArrayCodecBase.gatherContents(SoapArrayCodecBase.java:464)
         at weblogic.xml.schema.binding.CodecBase.serializeFill(CodecBase.java:279)
         at weblogic.xml.schema.binding.CodecBase.serialize_internal(CodecBase.java:216)
         at weblogic.xml.schema.binding.CodecBase.serialize(CodecBase.java:178)
         at weblogic.xml.schema.binding.RuntimeUtils.invoke_serializer(RuntimeUtils.java:188)...
    Here is code I use to register the mapping and the code I use to add the LinkedList to the call.
    TypeMappingRegistry registry = service.getTypeMappingRegistry();
    TypeMapping mapping = registry.getTypeMapping( SOAPConstants.URI_NS_SOAP_ENCODING );
    mapping.register( java.util.LinkedList.class,
    new QName("http://soapinterop.org/xsd", "LinkedList" ),
    new LinkedListCodec(),
    new LinkedListCodec() );
    QName linkedListName = new QName("http://soapinterop.org/xsd", "LinkedList");
    LinkedList test = new LinkedList();
    test.add("test");
    call.addParameter("linkedList", linkedListName, javax.xml.rpc.ParameterMode.IN);
    Can anyone help me figure out what the problem is?? I did this same thing for a String array and now I can't get it to work for a LinkedList. Thanks.

    what about below error:
    syntax error, parameterized types are only available if source level is 5.0
    Vector<String,String> a = new Vector<String,String>();
    doesn't work at all.
    i get the above syntax error with all the Collections types,
    ArrayDeque, LinkedList, Stack, HashTable, HashMap, . . .
    i think some package is something or anything else ?
    regards,
    rafi

  • Quick and Dirty Tree Mapping

    Hi, i'm trying to do a quick and simple mapping for categories.
    Something like...
    Vector v = new Vector();
    v = PatriotmemDB.getFAQCategories();
    FAQCategoryObj catObj = null;
    String catname = null;
    int catid = 0;
    int parent = 0;
    int counter = 0;
    int prev = 0;
    Vector catTree = new Vector();
    for(int j=0;j<v.size();j++) {
    catObj = (FAQCategoryObj)v.elementAt(j);
    parent = catObj.getCatID();
    if(parent == counter) {
    if(counter == prev) {
    catTree.elementAt(counter).add(catObj);
    } else {
    catTree.elementAt(counter) = new Vector();
    catTree.elementAt(counter).add(catObj);
    } else {
    counter++;
    I know this will give an error but basically break out each parent in separate Vectors so that when i loop through them i can test and show in a select list. My table retuns below...
    categoryid catname catdesc imglink order parent
    1 DRAM DRAM NULL 0 0
    2 Solid State Drives Solid State Drives NULL 0 0
    3 USB Flash Drives USB Flash Drives NULL 0 0
    4 Peripherals Peripherals NULL 0 0
    5 Torqx Torqx NULL 0 2
    6 Zephyr Zephyr NULL 0 2
    7 Xporter XT Boost Xporter XT Boost NULL 0 3
    8 Xporter Razzo Xporter Razzo NULL 0 3
    Where the parent is the last column.
    Thanks for your help

    OK, so you have a tree, and you want to product these kind of weird vector slices of the tree, presumably as input to something else.
    How is the tree implemented? It looks like a vector of some class, in which the tree structure is implicit in the relationship of some fields of the class, but not an actual tree (composed of nodes, with directed edges between the nodes, no cycles, and a single node is identified as root). Right?
    If so, I can imagine one way to do it would be to create a Map<Integer, Vector<TheClass>> Loop through the vector, looking at each class, get the parent reference (which I take to be an integer from your example), and then look up in the map the vector identified for that integer. (If it doesn't exist, create it and add it to the map.) Then add the given class to that vector. When you're done, take the values set from the map.
    If you have an actual explicit formal tree, then I'd suggest writing a simple recursive function to span it.
    By the way, Vector is kind of long in the tooth. The more canonical List implementations these days are ArrayList or LinkedList.

  • LinkedList.remove(Object) O(1) vs O(n)

    The LinkedList class documentation says the following:
    "All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index."
    Typically one expects the remove operation from a linkedlist to be O(1). (for example [here on wikipedia|http://en.wikipedia.org/wiki/Linked_list] )
    This is in theory true however typically in the implementation of a LinkedList internally nodes (or Entry<E> in the case of the java implementation) are made that are wrappers around the actual objects inserted in the list. These nodes also contain the references to the next and previous nodes.
    These nodes can be removed from the linked list in O(1). However if you want to remove an a object from the list, you need to map it to the node to be removed. In the java implementation they simply search for the node in O(n). (It could be done without searching but this would require some mapping which requires more memory.)
    The java implementation can be seen here:
        public boolean remove(Object o) {
            if (o==null) {
                for (Entry<E> e = header.next; e != header; e = e.next) {
                    if (e.element==null) {
                        remove(e);
                        return true;
            } else {
                for (Entry<E> e = header.next; e != header; e = e.next) {
                    if (o.equals(e.element)) {
                        remove(e);
                        return true;
            return false;
        }It seems to be a common misconception that this method runs in O(1) while it actually runs in O(n). For example [here in this cheat sheet|http://www.coderfriendly.com/2009/05/23/java-collections-cheatsheet-v2/] and [in this book|http://oreilly.com/catalog/9780596527754/]. I think quite a lot of people think this methode runs in O(1). I think it should be made explicitly clear in the documentation of the class and the method that it runs in O(n).
    On a side note: the remove() operation from the LinkedList iterator does perform in O(1).

    I agree. It's not at all clear what the objection here is.
    To add to Jeff's answer: the remove operation on the LinkedListIterator is O(1) because you don't have to search for the node to unlink - the iterator already has a pointer to it.
    I tend to think of two different operations:
    - unlink - an operation specific to a linked datastructure which removes a given node from the datastructure and completes in O(1)
    - remove - an operation which searches for a given object in the data structure and then removes the node containing that object (using the unlink operation in the case of a linked datastructure). The performance of this depends on the performance of the search and unlink operations. In an unsorted linked list (e.g. the Java LinkedList) the search operation is O(n). So this operation is O(n).

Maybe you are looking for

  • How do I sync my iPod nano 7 with my HP Laptop and 4s iPhone?

    How do I sync my iPod nano 7 with my HP laptop and my iPhone 4S?

  • 2.1 Bug with uploaded files?

    Hi, I'm not sure if we're posting bugs to the forum but i'll just post it up here anyway.. I'm using HTMLDB 2.1 running on Oracle Express and uploaded a javascript file (into 'static files') so that i could reference it from a page. My page was worki

  • Planning application Business rules and Rulesets are disappearing

    Hi, Our Planning application Business rules and Rulesets are disappearing after services refresh. *2011-09-28 09:45:24,740 WARN Thread-16 com.hyperion.calcmgr.common.GenericLogger - [Hyperion][Oracle JDBC Driver][Oracle]ORA-00001: unique constraint (

  • SAP F&R:: Trend + Seasonality

    Hi Guys, I have been trying to generate forecast for a set of consumption data where the data has a trend and a seasonality component. However, when I generate the forecast, the system at best ONLY takes into account the trend in the forecast. The se

  • Continued/ linking .swf file to Dreamweaver

    Hi , All I need is to link my swf file to a link in my HTML page, the swf file has its own control buttons created in Captivate that I need them to be shown in the swf file ratherthan new ones! and I need all this to be shown as a smaller window in t