Equals on array

Hi, guys, recently, i wondered about something : how come "equals" on an array will return true if and only if the reference is the same?
what i mean is illustrated by the following code:
     public static void main (String[] args) {
          int[] i1 = {1, 2, 3};
          int[] i2 = {1, 2, 3};
          int[] i3 = i1.clone();
          int[] i4 = i1;
          System.out.println(i1.equals(i2));
          System.out.println(i1.equals(i3));
          System.out.println(i1.equals(i4));
          String[] s1 = {"a", "b", "c"};
          String[] s2 = {"a", "b", "c"};
          String[] s3 = s1.clone();
          System.out.println(s1.equals(s2));
          System.out.println(s1.equals(s3));
          System.out.println(s2.equals(s3));
     }which gives the following output:
false
false
true
false
false
falsewouldn't it be useful to have "==" as a physical operator, and ".equals" as a logical operator like for any object class, but for arrays?
the equals on 'this' array could call equals on each index of the array (meaning, each object contained in the array) and compare it to the matching index of the other array, and return true if the object's equals returns true for every index

jwenting wrote:
calvino_ind wrote:
Hi, guys, recently, i wondered about something : how come "equals" on an array will return true if and only if the reference is the same?
because that's how it's defined, obviously.
wouldn't it be useful to have "==" as a physical operator, and ".equals" as a logical operator like for any object class, but for arrays?
no.
The array is the same if the array is the same. Containing references to different objects containing themselves the same data does not make it the same.
It doesn't even make the content of the array the same.what about two arrays that have a different reference, but which hold references to the same objects, in the same order? like:
String s1 = new String("Hello");
String s2 = new String("World");
String[] ss1 = {s1, s2};
String[] ss2 = {s1, s2};

Similar Messages

  • Equals() on arrays

    Can anybody give me a hint pls why this code prints false?
    Aren't the arrays identical?
    class Test {
         public static void main(String[] args) {
              int ia1[] = { 1, 2 };
              int ia2[] = (int[])ia1.clone();
              System.out.println(ia1.equals(ia2));
    }

    Object.equals(Object obj) returns true ONLY IF both
    references point to the same object, no matter
    identical are the objects or not.Yes, but the method is quite often overloaded. Not for arrays though, and that applies to the toString method too...
    If you couldn't compare the equality of, say, two strings Java would be a very obscure language :)

  • Select Value Equal to Array

    I'm using Dreamweaver CS5 with PHP and a MySQL database.  I'm trying to read from an array (states[]) in the database that list all selected states a contractor might work in, i.e. WA,ID,OR... my insert record is savaing my array with the state abriviations with a coma in between with no space, which is fine with me.  My code for the insert record is:
    if (isset($_POST['states'])) {
                        $_POST['states'] = implode(',', $_POST['states']);
              } else {
                        $_POST['states'] = null;
    To test what my result needs to be, I have tried to hard code the Select Value Equal To box in the Dynamic List/Menu to WA which selects WA (Washington) fine. The Allow Multiple Selections checkbox is selected for this list/menu.  When I try to hard code more than one state like WA,ID, nothing is selected.  I have also tried to select WA ID and WAID.  What is the proper format of the Select Value Equal To in order to select multiple items. 
    Once the hardcoding is figured out I was going to try to figure out how to loop through in PHP and have it dynamically select from the record and echo (or otherwise print) in the proper format so multiple states from the array would be selected.  However, if someone out there has a sample, that would be great. 
    Thanks in advance for your help!
    Darren

    First, and maybe I'm reading this incorrectly, but shouldn't the "implode" in your example be "explode" because you have the array but you want to get the values out of it?
    Now I realize my next suggestion isn't what you want to hear but I used to think like you and store things in an array, loop an array, and then try to check the loop if certain values exist.  However, as time has taught me it's not necessarily the best way to store values that you will need for this type of instance.  Most of the time in instances like this, your user will be searching for contractors in a specific state.  So what I would recommend is creating another table with 2 columns:
    contractor_id (a way to identify the contractor, this will be a primary key, that will link to a key for the "contractor_id" in your original table)
    contractor_state (this will link an id to a state)
    One loop would be to query the contractor state, while the contractor ID is met and you could run a join to pull out the contractor states while the ID condition is met.  The other side is to pull out all the contractor IDs where the state criteria is met.  You would need to run a JOIN on the query to combine the original table with this new table if you wanted to pull out the contractor name along with the state just to name an example.
    A good article that you may want to read is the first answer from this StackOverflow question and the associated link in the response talking about normalization and about serializing data:
    http://stackoverflow.com/questions/1790481/php-mysql-storing-array-in-database

  • All the data that is equal within a certain range to be defined as equal in array

    Hi, I need to get some help!
    In edge detection, I get the result of all edges found in an array. When two or more edges is found close to eachother, I need to get them defined as one edge found.
    As an example, if the VI locate 10 edges, but 5 of them is close to eachother within a certain range, there will be only 6 result on the output.
    I'm quite new to Labview and will appreciate any sort of help

    I think I need help to solve the problem from scratch. As you can see in the picture it has been detected several edges in the middle of the picture. To the right in the picture you can see the array showing the Y-position of each edge detected. I need all edges that is within 30 pixels to eachother to be considered as one edge, and then compute the new array showing the position of the edges. 
    Attachments:
    example.JPG ‏95 KB

  • Stuck with making my event structure examine if two arrays are equal

    Hi there, I'm new to labview. I'm trying to write an event structure; examining if one array equals another array. The program will carry on if they are equal, otherwise it will continue checking... Any help is appreciated.
    My program is attached.. It is eventually going to be a memory game when I get it working..
    Sequence 1, case structure 10 is were I'm stuck with the case structure.
    Thank you in advance
    Attachments:
    attempt 2.vi ‏18 KB

    Seems to me like you should implement a true State Machine.  This way you can repeat states and/or jump states as needed.
    State Machine
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • What is the best way of dealing with an "implicit coercion" of an array to a sprite?

    Hello everyone!
         With continued help from this forum I am getting closer to having a working program. I look forward to being able to help others like myself once I finish learning the AS3 ropes.
         I will briefly explain what I am trying to achieve and then follow it up with my question.
    Background
         I have created a 12 x 9 random number grid that populates each cell with a corresponding image based on each cell's numeric value. I have also created a shuffle button that randomizes the numbers in the grid. The problem I am running into is getting my button-click event to clear the current images off the grid in order to assign new ones (i.e. deleting the display stack objects in order to place news ones in the same locations).
    Question
         My question is this: what is the best way to handle an implicit coercion from an array to a sprite? I have pasted my entire code below so that you can see how the functions are supposed to work together. My trouble apparently lies with not being able to use an array value with a sprite (the sprite represents the actual arrangement of the grid on the display stack while the array starts out as a number than gets assigned an image which should be passed to the sprite).
    ============================================================================
    package 
    import flash.display.MovieClip;
    import flash.display.DisplayObject;
    import flash.events.MouseEvent;
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.text.TextFormat;
    import flash.utils.getDefinitionByName;
    public class Blanko extends MovieClip
          // Holds 12*9 grid of cells.
          var grid:Sprite;
          // Holds the shuffle button.
          var shuffleButton:Sprite;
          // Equals 12 columns, 9 rows.
          var cols:int = 12;
          var rows:int = 9;
          // Equals number of cells in grid (108).
          var cells:int = cols * rows;
          // Sets cell width and height to 40 pixels.
          var cellW:int = 40;
          var cellH:int = 40;
          // Holds 108 cell images.
          var imageArray:Array = [];
          // Holds 108 numerical values for the cells in the grid.
          var cellNumbers:Array = [];
          // Constructor calls "generateGrid" and "makeShuffleButton" functions.
          public function Blanko()
               generateGrid();
               makeShuffleButton();
      // Creates and displays the 12*9 grid.
      private function generateGrid():void
           grid = new Sprite;
           var i:int = 0;
           for (i = 0; i < cells; i++)
                cellNumbers.push(i % 9 + 1);
           trace("Before shuffle: ", cellNumbers);
           shuffleCells(cellNumbers);
           trace("After shuffle: ", cellNumbers);
           var _cell:Sprite;
           for (i = 0; i < cells; i++)
                // This next line is where the implicit coercion occurs. "_cell" is a sprite that tries
                   to temporarily equal an array value.
                _cell = drawCells(cellNumbers[i]);
                _cell.x = (i % cols) * cellW;
                _cell.y = (i / cols) * cellH;
                grid.addChild(_cell);
      // Creates a "shuffle" button and adds an on-click mouse event.
      private function makeShuffleButton():void
           var _label:TextField = new TextField();
           _label.autoSize = "center";
           TextField(_label).multiline = TextField(_label).wordWrap = false;
           TextField(_label).defaultTextFormat = new TextFormat("Arial", 11, 0xFFFFFF, "bold");
           _label.text = "SHUFFLE";
           _label.x = 4;
           _label.y = 2;
           shuffleButton = new Sprite();
           shuffleButton.graphics.beginFill(0x484848);
           shuffleButton.graphics.drawRoundRect(0, 0, _label.width + _label.x * 2, _label.height +
                                                _label.y * 2, 10);
           shuffleButton.addChild(_label);
           shuffleButton.buttonMode = shuffleButton.useHandCursor = true;
           shuffleButton.mouseChildren = false;
           shuffleButton.x = grid.x + 30 + grid.width - shuffleButton.width;
           shuffleButton.y = grid.y + grid.height + 10;
           this.addChild(shuffleButton);
           shuffleButton.addEventListener(MouseEvent.CLICK, onShuffleButtonClick);
      // Clears cell images, shuffles their numbers and then assigns them new images.
      private function onShuffleButtonClick():void
       eraseCells();
       shuffleCells(cellNumbers);
       trace("After shuffle: ", cellNumbers);
       for (var i:int = 0; i < cells; i++)
        drawCells(cellNumbers[i]);
      // Removes any existing cell images from the display stack.
      private function eraseCells(): void
       while (imageArray.numChildren > 0)
        imageArray.removeChildAt(0);
      // Shuffles cell numbers (randomizes array).
      private function shuffleCells(_array:Array):void
       var _number:int = 0;
       var _a:int = 0;
       var _b:int = 0;
       var _rand:int = 0;
       for (var i:int = _array.length - 1; i > 0; i--)
        _rand = Math.random() * (i - 1);
        _a = _array[i];
        _b = _array[_rand];
        _array[i] = _b;
        _array[_rand] = _a;
      // Retrieves and assigns a custom image to a cell based on its numerical value.
      private function drawCells(_numeral:int):Array
       var _classRef:Class = Class(getDefinitionByName("skin" + _numeral));
       _classRef.x = 30;
       imageArray.push(_classRef);
       imageArray.addChild(_classRef);
       return imageArray;
    ===========================================================================
         Any help with this is greatly appreciated. Thanks!

    Rothrock,
         Thank you for the reply. Let me address a few things here in the hopes of allowing you (and others) to better understand my reasoning for doing things in this manner (admittedly, there is probably a much better/easier approach to what I am trying to accomplish which is one of the things I hope to learn/discover from these posts).
         The elements inside my "imageArray" are all individual graphics that I had imported, changed their type to movie clips using .Sprite as their base class (instead of .MovieClip) and then saved as classes. The reason I did this was because the classes could then be referenced via "getDefinitionByName" by each cell value that was being passed to it. In this grid every number from 1 to 9 appears randomly 12 times each (making the 108 cells which populate the grid). I did not, at the time (nor do I now), know of a better method to implement for making sure that each image appears in the cell that has the corresponding value (i.e. every time a cell has the value of 8 then the custom graphic/class "skin8" will be assigned to it so that the viewer will be able to see a more aesthetically pleasing numerical representation, that is to say a slightly more fancy looking number with a picture behind it). I was advised to store these images in an array so that I could destroy them when I reshuffle the grid in order to make room for the new images (but I probably messed up the instructions).
         If the "drawCell" function only returns a sprite rather than the image array itself, doesn't that mean that my "eraseCells" function won't be able to delete the array's children as their values weren't first returned to the global variable which my erasing function is accessing?
         As for the function name "drawCells," you have to keep in mind that a) my program has been redesigned in stages as I add new functionality/remove old functionality (such as removing text labels and formatting which were originally in this function) and b) that my program is called "Blanko."
         I will try and attach an Illustrator exported JPG file that contains the image I am using as the class "skin7" just to give you an example of what I'm trying to use as labels (although it won't let me insert it here in this post, so I will try it in the next post).
    Thank you for your help!

  • Equals in Hashtable

    I have a Hashtable which maps int[] to an array of objects called cell.
    Declared like this Hastable<int[], cell[]> tableMy problem is this. The hashtable uses Object.equals - but I want to use Arrays.equals. For instance:
    int[] keyLookup = new int[] {0,1,2,3};
    if(table.containsKey(keyLookup)){
    }However this doesn't work because:
    int[] one = new int[] {0,1,2,3};
    int[] two = new int[] {0,1,2,3};one.equals(two) is false;
    I want the behaviour of Arrays.equals(one, two) is true.
    Is it possible to achieve this? Because I don't want to have to enumerate over all the keys performing Array.equals!

    This has not entirely solved my problem.
    I now have what I've called a Signature, which models the int[] and have overridden the equals method to use the Arrays.equals method. e.g.:
    int[] one = new int[] {0,1,2,3};
    int[] two = new int[] {0,1,2,3};
    System.out.println("Object equals = " + one.equals(two));
    System.out.println("Arrays equals = " + Arrays.equals(one, two));
    Signature sOne = new Signature(one);
    Signature sTwo = new Signature(two);
    System.out.println("Signature equals = " + sOne.equals(sTwo));Which is great and now gives me the desired behaviour, here's the output
    Object equals = false
    Arrays.equals = true
    Signature equals = true
    But the problem is I have not overridden the hashCode method; and so two objects which are now equal return different hashCodes - resulting in Hashtable.get/containsKey being incorrect.
    I could write an implementation of this based on the values in the integer array of the Signaure but I am wary of doing this because it could be easy to make a mistake.
    Any suggestions on either how to safely override hashCode or an alternative approach?

  • A suggestion : use "loop array list" instead of ArrayList / LinkedList

    ArrayList is good at:
    get / set by index : O(1)
    appending : O(log(n))
    remove last : O(1)
    and very bad at:
    add middle : O(n)
    remove from middle : O(n)
    LinkedList is good at:
    fast remove from middle, if your iteraror already goes there : O(1)
    convenient methods : addFirst, addLast, removeFirst, removeLast : O(1)
    and very bad at :
    get / set by index : O(n)
    here I want to make a suggestion : use "loop array list" instead of the ArrayList and LinkedList.
    a "loop array list" is based on array, just like ArrayList. But it has 2 member-variables : the start position, and the real size. the start position can be anywhere within array.length. an element of index "i" is stored in array[ start + i ], and when (start + i > array.length), loop to the beginning of the array; when (start + i < 0), loop to the end of the array.
    this "loop array list" has all the good sides:
    get / set by index : O(1)
    add first / last : O(log(n))
    remove first / last : O(log(n))
    add / remove from middle : O(n)
    (note : because we shrink the backup-array when the real size is too small, add / remove operation take O(log(n)) now.)
    the only problem is : add / remove from middle. let's take a look at it.
    1. the LinkedList does NOT really add/remove from middle in O(1), you has to locate the element, which is O(n).
    2. O(n) is acceptable, O(n^2) is not acceptable. try this : keep removing first element from an very big ArrayList ( size>10^6 ) until it's empty.
    the fact is, any list can perform batch-remove / batch-add operation in O(n) instead of O(n^2). it's easy : allocate a new list, iterate the original list, copy the element into the new list if condition is satisfied.
    so, instead of "remove from middle", what we need is a new methods : removeAllByCondition( Condition condition ), and now the batch-remove operation can be done in O(n)
    here is an implementation of mine. I've tested it on my computer( 512mem + 2G cpu, win2k + jdk1.5 ), it's amazing, just a little slower then ArrayList when add last, and a liitle slower then LinkedList when batch-remove. in all other cases, it's far more better then those 2 kinds of List.
    // source code : List2
    import java.util.AbstractList;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.NoSuchElementException;
    import java.util.Set;
    public final class List2<T> extends AbstractList<T> {
    private static int initialArrayLength = 4;
    private T[] array;
    private int start;
    private int size;
    private void init( T[] newArray, int start_a, int size_a ) {
    array = newArray;
    start = start_a;
    size = size_a;
    @SuppressWarnings("unchecked")
    private void init() {
    init( (T[]) new Object[ initialArrayLength ], 0, 0 );
    public List2() {
         init();
    @SuppressWarnings("unchecked")
    public List2( Collection<? extends T> collection ) {
         init(
              collection.toArray( (T[]) new Object[ collection.size() * 11 / 10 + 1 ] ),
              0,
              collection.size()
    private List2( T[] array_a, int start_a, int size_a ) {
         init( array_a, start_a, size_a );
    @SuppressWarnings("unchecked")
    public static <TT> List2<TT> createV( TT... elements ) {
         TT[] array = (TT[]) new Object[ elements.length * 11 / 10 + 1 ];
         System.arraycopy( elements, 0, array, 0, elements.length );
         return new List2<TT>( array, 0, elements.length );
    public static List2<Double> create( double... elements ) {
         Double[] array = new Double[ elements.length * 11 / 10 + 1 ];
         for( int i=0; i < elements.length; i++ )
              array[i] = elements;
         return new List2<Double>( array, 0, elements.length );
    public static List2<Integer> create( int... elements ) {
         Integer[] array2 = new Integer[ elements.length * 11 / 10 + 1 ];
         for( int i=0; i < elements.length; i++ )
              array2[i] = elements[i];
         return new List2<Integer>( array2, 0, elements.length );
    public static List2<Character> create( char... elements ) {
         Character[] array2 = new Character[ elements.length * 11 / 10 + 1 ];
         for( int i=0; i < elements.length; i++ )
              array2[i] = elements[i];
         return new List2<Character>( array2, 0, elements.length );
    public static List2<Character> create( String s ) {
         return create( s.toCharArray() );
    public List2<T> clone() {
         return new List2<T>( this );
    // basic
    public int size() {
         return size;
    private int index( int index ) {
         int i = start + index;
         if( i >= array.length )
              i -= array.length;
         return i;
    public T get( int d ) {
         if( d < 0 || d >= size )
              throw new IndexOutOfBoundsException();
         if( size == 0 )
              throw new NoSuchElementException();
         return array[ index( d ) ];
    public T set( int index, T element ) {
         if( index < 0 || index >= size )
              throw new IndexOutOfBoundsException();
         int i = index( index );
         T oldElement = array[i];
         array[i] = element;
         return oldElement;
    @SuppressWarnings("unchecked")
    private void copyAndSetToNewArray( int newArrayLength ) {
         T[] newArray = (T[]) new Object[ newArrayLength ];
         for( int i=0; i<size; i++ )
              newArray[i] = array[ index( i ) ];
         init( newArray, 0, size );
    public void addFirst( T element ) {
         if( size == array.length )
              copyAndSetToNewArray( size * 3 / 2 + 1 );
         int i = index( array.length - 1 );
         array[ i ] = element;
         start = i;
         size++;
    public void addLast( T element ) {
         if( size == array.length )
              copyAndSetToNewArray( size * 3 / 2 + 1 );
         array[ index( size ) ] = element;
         size++;
    public T removeFirst() {
         if( size == 0 )
              throw new NoSuchElementException();
         T oldElement = array[ start ];
         array[ start ] = null;
         start = index( 1 );
         size--;
         if( array.length > size * 2 + 1 )
              copyAndSetToNewArray( size * 11 / 10 + 1 );
         return oldElement;
    public T removeLast() {
         if( size == 0 )
              throw new NoSuchElementException();
         int i = index( size - 1 );
         T oldElement = array[i];
         array[i] = null;
         size--;
         if( array.length > size * 2 + 1 )
              copyAndSetToNewArray( size * 11 / 10 + 1 );
         return oldElement;
    @SuppressWarnings("unchecked")
    public int removeAll( ListCondition<T> condition ) {
         T[] newArray = (T[]) new Object[ array.length ];
         int iNew = 0;
         for( int i=0; i < size; i++ ) {
              T element = get( i );
              if( ! condition.isConditionSatisfied( this, i, element ) )
                   newArray[ iNew++ ] = element;
         int oldSize = size;
         init( newArray, 0, iNew );
         if( array.length > size * 2 + 1 )
              copyAndSetToNewArray( size * 11 / 10 + 1 );
         return size - oldSize;
    // aux
    public boolean equals(Object obj) {
         if( obj == this )
         return true;
         if( obj instanceof List2 ) {
              List2 that = (List2) obj;
              if( this.size != that.size )
                   return false;
              for( int i=0; i < size; i++ )
                   if( ! Tools.equals( this.array[ this.index(i) ], that.array[ that.index(i) ] ) )
                        return false;
              return true;
         if( obj instanceof List ) {
              List that = (List) obj;
              if( this.size != that.size() )
                   return false;
              Iterator thatIter = that.iterator();
              for( int i=0; i < size; i++ )
                   if( ! Tools.equals( this.array[ this.index(i) ], thatIter.next() ) )
                        return false;
              return true;
         return true;
    public int hashCode() {
         int hashCode = 1;
         for( int i=0; i < size; i++ ) {
              T element = array[ index( i ) ];
         hashCode = 31*hashCode + ( element==null ? 0 : element.hashCode() );
         return hashCode;
    public boolean isEmpty() {
         return size == 0;
    public T getFirst() {
         return get( 0 );
    public T getLast() {
         return get( size() - 1 );
    public T getRandom() {
         return get( (int) (Math.random() * size) );
    public int indexOf( Object element ) {
         for( int i=0; i < size; i++ )
              if( Tools.equals( array[ index( i ) ], element ) )
                   return i;
         return -1;
    public int lastIndexOf( Object element ) {
         for( int i=size-1; i >= 0; i-- )
              if( Tools.equals( array[ index( i ) ], element ) )
                   return i;
         return -1;
    public boolean contains( Object element ) {
         return indexOf( element ) != -1;
    public boolean add( T element ) {
         addLast( element );
         return true;
    @Deprecated
    public void add( int index, T element ) {
         throw new UnsupportedOperationException();
    public T remove() {
         return removeFirst();
    @Deprecated
    public boolean remove( Object element ) {
         throw new UnsupportedOperationException( "use removeAll( Condition ) instead" );
    @Deprecated
    public T remove( int index ) {
         throw new UnsupportedOperationException( "use removeAll( Condition ) instead" );
    public void clear() {
         init();
    public Object[] toArray() {
         Object[] result = new Object[ size ];
         for( int i=0; i < size; i++ )
         result[i] = array[ index( i ) ];
         return result;
    @SuppressWarnings("unchecked")
    public <TT> TT[] toArray( TT[] a ) {
    if( a.length < size )
    a = (TT[]) java.lang.reflect.Array.newInstance( a.getClass().getComponentType(), size );
    for( int i=0; i < size; i++ )
    a[i] = (TT) array[ index( i ) ];
    if( a.length > size )
         a[size] = null;
    return a;
    @SuppressWarnings("unchecked")
    public void sort() {
         Object[] a = toArray();
         Arrays.sort( a );
         for( int i=0; i < size; i++ )
              array[ i ] = (T) a[ i ];
         start = 0;
    @SuppressWarnings("unchecked")
    public void sortDesc() {
         Object[] a = toArray();
         Arrays.sort( a );
         for( int i=0, j=size-1; i < size; i++, j-- )
              array[ i ] = (T) a[ j ];
         start = 0;
    @SuppressWarnings("unchecked")
    public void sort( Comparator<T> comparator ) {
         T[] a = (T[]) toArray();
         Arrays.sort( a, comparator );
         for( int i=0; i < size; i++ )
              array[ i ] = a[ i ];
         start = 0;
    @SuppressWarnings("unchecked")
    public void sortDesc( Comparator<T> comparator ) {
         T[] a = (T[]) toArray();
         Arrays.sort( a, comparator );
         for( int i=0, j=size-1; i < size; i++, j-- )
              array[ i ] = a[ j ];
         start = 0;
    public String toString( String delimiter ) {
         return toString( "", delimiter, "", size() );
    public String toString( String prefix, String delimiter, String suffix, int max ) {
         StringBuffer stringBuffer = new StringBuffer( prefix );
         int dest = Math.min( max, size );
         for( int i=0; i < dest; i++ ) {
              stringBuffer.append( get(i) );
              if( i < dest - 1 )
                   stringBuffer.append( delimiter );
         if( size > max )
              stringBuffer.append( "...(" ).append( size() - max ).append( " more)" );
         stringBuffer.append( suffix );
         return stringBuffer.toString();
    // batch operation
    public boolean containsAll( Collection<?> that ) {
         Set<Object> thisSet = new HashSet<Object>( this );
         for( Object element : that )
              if( ! thisSet.contains( element ) )
                   return false;
         return true;
    @SuppressWarnings("unchecked")
    public List2<T> subList( int fromIndex, int toIndex ) {
         if( fromIndex < 0 || toIndex > size || toIndex < fromIndex )
              throw new IndexOutOfBoundsException();
         int newSize = toIndex - fromIndex;
         T[] newArray = (T[]) new Object[ newSize * 11 / 10 + 1 ];
         for( int i=fromIndex, iNew=0; i < toIndex; i++, iNew++ )
              newArray[ iNew ] = array[ index( i ) ];
         return new List2<T>( newArray, 0, newSize );
    public void addV( T... that ) {
         for( T element : that )
              addLast( element );
    public boolean addAll( Collection<? extends T> that ) {
         for( T element : that )
              addLast( element );
         return ! that.isEmpty();
    @Deprecated
    public boolean addAll( int index, Collection<? extends T> c ) {
         throw new UnsupportedOperationException();
    public void removeRest( T element ) {
         int position = lastIndexOf( element );
         if( position == -1 )
              return;
         while( ! Tools.equals( element, removeLast() ) );
    public void removeAllEquals( final T element ) {
         removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T currentElement) {
              return currentElement.equals( element );
    public void removeAllBetween( final T from, final T to ) {
         removeAll( new ListCondition<T>() {
              @SuppressWarnings("unchecked")
              public boolean isConditionSatisfied(List2 list, int index, T element) {
                   if( from != null && ((Comparable) from).compareTo( element ) > 0 )
                        return false;
                   if( to != null && ((Comparable) to).compareTo( element ) <= 0 )
                        return false;
                   return true;
    public boolean retainAll( Collection<?> that ) {
         final Set<Object> thatSet = new HashSet<Object>( that );
         int removeCount = removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T element) {
              return ! thatSet.contains( element );
         return removeCount > 0;
    public boolean removeAll( Collection<?> that ) {
         final Set<Object> thatSet = new HashSet<Object>( that );
         int removeCount = removeAll( new ListCondition<T>() { public boolean isConditionSatisfied(List2 list, int index, T element) {
              return thatSet.contains( element );
         return removeCount > 0;
    // unit test
    private static int maxTestCount = 1000 * 1000;
    public static void unitTest() throws Exception {
         // thest thoese methods for one time
         Tools.ensureEquals( new List2(), new ArrayList() );
         Tools.ensureNotEquals( List2.create( "abcde" ), new ArrayList() );
         Tools.ensureNotEquals( List2.create( "abcde" ), List2.create( "abcdef" ) );
         final List<Double> list1 = new ArrayList<Double>();
         final List2<Double> list2 = new List2<Double>();
         Runnable[] tasks = new Runnable[] {
              // test those methods that do NOT change the list
              new Runnable() { public void run() {
                   Tools.ensureEquals( new List2<Double>( list1 ), list1 );
                   Tools.ensureEquals( List2.createV( list1.toArray() ), list1 );
                   Tools.ensureEquals( List2.createV( list1.toArray( new Double[0] ) ), list1 );
                   double[] doubles = new double[ list1.size() ];
                   int i = 0;
                   for( double d : list1 )
                        doubles[i++] = d;
                   Tools.ensureEquals( List2.create( doubles ), list1 );
                   Tools.ensure( list1.isEmpty() == list2.isEmpty() );
                   Arrays.equals( list1.toArray(), list2.toArray() );
                   Tools.ensureEquals( list1, list2.clone() );
                   Double notExistElement = -2.0;
                   Tools.ensure( list1.indexOf( notExistElement ) == -1 );
                   Tools.ensure( list1.lastIndexOf( notExistElement ) == -1 );
                   Tools.ensure( list1.contains( notExistElement ) == false );
                   Tools.ensureEquals( list1.toString(), list2.toString() );
                   Tools.ensureEquals( list1.toString(), list2.toString() );
                   Tools.ensureEquals( list1.hashCode(), list2.hashCode() );
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.get(0).equals( list2.getFirst() ) );
                   Tools.ensure( list1.get(list1.size()-1).equals( list2.getLast() ) );
                   Double existRandomElement = list2.getRandom();
                   Tools.ensure( list1.contains( existRandomElement ) );
                   Tools.ensure( list2.contains( existRandomElement ) );
                   Tools.ensure( list1.indexOf( existRandomElement ) == list2.indexOf( existRandomElement ) );
                   Tools.ensure( list1.indexOf( existRandomElement ) == list2.indexOf( existRandomElement ) );
                   int from = (int) (Math.random() * list1.size());
                   int to = (int) (Math.random() * (list1.size()+1));
                   if( from > to ) {
                        int t = from;
                        from = to;
                        to = t;
                   Tools.ensureEquals( list1.subList( from, to ), list2.subList( from, to ) );
              // test those methods that change the list
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int i = (int) (Math.random() * list1.size());
                   double d = Math.random();
                   list1.set( i, d );
                   list2.set( i, d );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int i = (int) (Math.random() * list1.size());
                   Tools.ensure( list1.get( i ).equals( list2.get( i ) ) );
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( 0, d );
                   list2.addFirst( d );
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( d );
                   list2.addLast( d );
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( d );
                   list2.addLast( d );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.remove( 0 ).equals( list2.removeFirst() ) );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.remove( list1.size() - 1 ).equals( list2.removeLast() ) );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int i = 0;
                   for( Iterator<Double> iter=list1.iterator(); iter.hasNext(); i++ ) {
                        iter.next();
                        if( i % 3 == 0 )
                             iter.remove();
                   list2.removeAll( new ListCondition<Double>() { public boolean isConditionSatisfied(List2 list, int index, Double element) {
                        return index % 3 == 0;
              new Runnable() { public void run() {
                   double d = Math.random();
                   list1.add( d );
                   list2.add( d );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   Tools.ensure( list1.remove(0).equals( list2.remove() ) );
              new Runnable() { public void run() {
                   if( list1.isEmpty() )
                        return;
                   int r = (int) (Math.random() * list1.size());
                   Double element = list1.get( r );
                   int index = list1.lastIndexOf( element );
                   for( int i=list1.size()-1; i>=index; i-- )
                        list1.remove( i );
                   list2.removeRest( element );
              new Runnable() { public void run() {
                   list2.removeRest( Math.random() - 2 );
              new Runnable() { public void run() {
                   list1.clear();
                   list2.clear();
              new Runnable() { public void run() {
                   Collections.sort( list1 );
                   list2.sort();
              new Runnable() { public void run() {
                   Collections.sort( list1 );
                   Collections.reverse( list1 );
                   list2.sortDesc();
              new Runnable() { public void run() {
                   Comparator<Double> comparator = new Comparator<Double>() { public int compare(Double o1, Double o2) {
                        return o1.toString().substring(2).compareTo( o2.toString().substring(2) );
                   Collections.sort( list1, comparator );
                   list2.sort( comparator );
              new Runnable() { public void run() {
                   Comparator<Double> comparator = new Comparator<Double>() { public int compare(Double o1, Double o2) {
                        return o1.toString().substring(2).compareTo( o2.toString().substring(2) );
                   Collections.sort( list1, comparator );
                   Collections.reverse( list1 );
                   list2.sortDesc( comparator );
              new Runnable() { public void run() {
                   Double notExistElement = -2.0;
                   list2.removeAllEquals( notExistElement );
                   Tools.ensureEquals( list1, list2 );
                   list2.removeAllBetween( 0.5, 0.6 );
                   for( Iterator<Double> iter=list1.iterator(); iter.hasNext(); ) {
                        double d = iter.next();
                        if( d >= 0.5 && d < 0.6 )
                             iter.remove();
                   Tools.ensureEquals( list1, list2 );
         System.out.print( "test List2 " );
         for( int i=0; i < maxTestCount; i++ ) {
              tasks[ (int) (Math.random() * tasks.length) ].run();
              Tools.ensureEquals( list1, list2 );
              if( i % (maxTestCount/10) == 0 )
                   System.out.print( "." );
         System.out.println( " ok" );
    // source code : ListCondition
    public interface ListCondition<T> {
    boolean isConditionSatisfied( List2 list, int index, T element );

    Hi,
    I have the following statement:
    private List list = new ArrayList();
    why not use private ArrayList list = new
    ArrayList()?
    I know ArrayList implements List, so list has a wide
    scope, right? What's the benefit?
    Thanks,
    JieBy using the interface you are not tied to a specific implementation.
    Later, you may determine that using a LinkedList is more efficient to your specific code and then all you need to do is change the statement to:
    private List list = new LinkedList();As long as you are not casting the list reference to ArrayList (or something along those lines) you would not need to change anything else.

  • Get the number of elements in Array

    Hi everyone,
    Could anyone give me idea on how to get the number of elements in an Array (not number of rows) ?
    I tried to find that in both property node and array functions but nothing.
    Thanks,
    -Kun

    You are going to have to provide some proof that the Array Size does not work correctly. Right click on the input to it and select 'Create Indicator'. Run the VI. Go to the front panel and select 'Edit>Make Current Values Default'. Save the VI and attach it to your post.
    You can also check the array size yourself. Right click on the index display of the array and select 'Advanced>Show Last Element'. I will bet you that number shown is equal to Array Size -1.
    p.s. The number of elements in an array is equal to the number of rows in a 1D array. If you define the number of elements as anything else, you are mistaken.
    Message Edited by Dennis Knutson on 04-21-2009 10:40 AM

  • Testing Object Equality using Serialization

    Hey everyone! I was wondering if somebody could help me figure out how to compare two objects using serialization.
    I have two objects that I'm trying to compare. Both of these objects extend a common "Model" class that has a method getSerialized() that returns a serialized form of an instance, shown below:
              // Serialize the object to an array
             ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
             ObjectOutputStream oos;
              try {
                   oos = new ObjectOutputStream(baos);
                  oos.writeObject(this);
                  oos.close();
              } catch (IOException e) {
                   e.printStackTrace();
             //Deserialize array into a String array
             return baos.toByteArray();This Model class also has an equals(Model obj) method that allows for the current model object to be compared to a model object that is passed in:
            //Store both models' serialized forms into byte arrays
            byte [] thisClass = this.getSerialized();
            byte [] otherClass = obj.getSerialized();This is where things get a little funny. The byte arrays don't equal - one array is a byte larger than the other. If a byte-by-byte comparison is done, the arrays are equal for the first 15-20% and then not equal for the rest. If I deserialize the byte arrays back into Models and do a toString() on those models, I find that they are equal.
    I have a feeling there's something about the serialization process that I don't fully comprehend. Is there a way to properly implement object comparison using serialization?
    Thanks in advance!

    When you serialize an object, you also serialize the entire tree of references based on that object (except for transient variables). That tree is the complicated business you described there. Serialization stores all the objects in the tree, along with data that explains which objects refer to which other objects. Furthermore if the tree is actually a graph, and there are multiple ways to get to an object, it still only stores each object once. I don't see any reason to believe that all that relationship data would be encoded identically for a pair of trees that you deemed to be equal. And your experiment shows that indeed it isn't.

  • An issue with arrays

    I am trying to write an applet which accepts five integers from the user, stores them in an array and then outputs them to a JTextArea. That bit is fine. But I also need to write it so that if the user enters two identical integers then it does not output the duplicate. (This is an exercise from Deitel & Deitel - yes, I'm a beginner! And I am aware that it mixes awt with swing...but that's what the book asks for).
    This is what I have written so far:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class InclusiveArray extends JApplet implements ActionListener {
         JLabel promptLabel;
         JTextField inputField;
         JTextArea outputField;
         int[] array = new int[5];
         int i = 0;
         String output = "The array contains: ";
         //create GUI
         public void init()
              Container container = getContentPane();
              container.setLayout(new FlowLayout());
              promptLabel = new JLabel("Enter a whole integer: ");
              inputField = new JTextField(10);
              inputField.addActionListener(this);
              outputField = new JTextArea(20, 20);
              container.add(promptLabel);
              container.add(inputField);
              container.add(outputField);
         } //end method init
         public void actionPerformed(ActionEvent event)
              array[i] = Integer.parseInt(event.getActionCommand());
              ++i;
              output += array[i] + " ";
              if (i>0)
              if (array[i] != array[0] && array != array[1] && array[i] != array[2] && array[i] != array[3] && array[i] != array[4])
                   output += array[i] + " ";
              /*else
                   output += " same ";*/
              outputField.setText(output);
              output = "\n The array now contains: ";
    This works, but, of course, the applet stops outputting integers as soon as it gets to array != array[1] because, of course, array[1] will always be equal to array[1].
    I am trying to find a way to compare the integer with every elements in the array apart from the integer itself.
    I found a way to compare each integer with the integer before it, in the array. And that worked - but it's not exactly what I need.
    Can anybody point me in the right direction?
    -Eoghain
    Message was edited by:
            Eoghain                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    Thank you all for your help. I decided to use a method to sort the array as I'm still not familiar with HashMap or LinkedHashSet. I'll go and read up on them now...
    In the meantime, here's my code. I have a question - I spent a while playing around with the code but I found that my output always contained only 4 elements when, in fact, the array contained 5 (this was verified by outputting the contents of the array to the screen using System.out.println). I solved this by initializing the array with 6 elements instead of 5. There is now a 'wasted' zero at the end which does not show up in the output.
    How could I do this with a 5-elements array? I'm sure the answer is staring me in the face, but I can't seem to find it!
    /*An applet to input 5 numbers, each of which is between 10 and 100 inclusive.
      As each number is read, display it only if it is not a duplicate of a number
      already read. Use the smallest possible array. Display results in a JTextArea.
      Use setText to update the results after each value is input by the user. */
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class InclusiveArray2 extends JApplet implements ActionListener {
         JLabel promptLabel;
         JTextField inputField;
         JTextArea outputField;
         int[] array = {0, 0, 0, 0, 0, 0};
         int i = 0;
         String output = "The array contains: ";
         //create GUI
         public void init()
              Container container = getContentPane();
              container.setLayout(new FlowLayout());
              promptLabel = new JLabel("Enter a whole integer: ");
              inputField = new JTextField(10);
              inputField.addActionListener(this);
              outputField = new JTextArea(20, 20);
              container.add(promptLabel);
              container.add(inputField);
              container.add(outputField);
         } //end method init
         public void actionPerformed(ActionEvent event)
              array[i] = Integer.parseInt(event.getActionCommand());
              ++i;
              for(int z = 0; z < array.length; z++)
              System.out.print("The array is now: " + array[z] + "\n");
              if (i == array.length-1)
                   sortArray(array);
         public void sortArray(int[] array2)
              //loop to control number of passes
              for (int pass = 1; pass < array2.length; pass++)
                   //loop to control number or comparison
                   for (int element = 0; element < array2.length-2; element++)
                        //compare side-by-side elements and swap if first > second
                        if (array2[element] > array2[element+1])
                             swap(array, element, element+1);
              buildOutput(array2);
         public void swap(int array4[], int first, int second)
              int hold; //temp holding area for swap
              hold = array4[first];
              array4[first] = array4[second];
              array4[second] = hold;
         public void buildOutput(int[] array3)
              for (int y = 0; y < array3.length-1; y++)
                   if(array[y+1] != array[y])
                        output += array3[y] + " ";
              outputField.setText(output);
              output = "\n The array now contains: ";
    }Thanks in advance,
    -Eoghain

  • Control array's scrollbar shows more rows than dimensions

    When an array's dimension and Number of Rows property are set to the same value, its vertical scrollbar is shown and implies there is one more row available in the array than the actual array size.
    This happen only if the array is a control, not when it is an indicator.  As an indicator, no scrollbar is shown at run time.  In edit mode, a scrollbar is shown when as an indicator.
    Is there a way to not have the scollbar appear if the number of rows equals the array size yet have it appear when the number of rows is less than the array size ?
    Example vi attached.
    Attachments:
    Array scroll bar dimension.vi ‏18 KB

    Jennifer,
    In practice, the number of displayed array rows is restricted so that only enough rows are shown to remain within the bounds of the front panel.  Otherwise as the array size is increased, the array will extend off the bottom of the screen.  My modified version shows this restriction.  But notice that as a control, the array shows one more dimension than it had been allocated to (and is shown as a disabled row).   In fact, clicking on the bottom arrow of the scollbar will continue to add more rows to the array control.
    Steve
    Attachments:
    Array scroll bar dimension.vi ‏22 KB

  • Execution time seems to be dependent on data when it shouldn't

    Hi, consider the code shown below.  It generates a 2D array of random values between 0 and 1 and then builds an array with values of 0 or 1 depending on whether the random value was greater than a predefined threshold or not. 
    I expected the running time to be independent of the value of the threshold, but there is significant difference (see results below). 
    Any idea why this would be?  Also note the difference in running time when autoindexing and when using an array-greater-than.

    I would say the way to determine whether it is the branch-prediction (i.e. sequence of comparison) or the 64/32 bit effect (actual data dependence independent of the order of comparisons) that is causing this behaviour is through the following experiment:
    Create 2 large equal-sized arrays with random values:  the first with random values between 0 and 1, and the second with the first half filled with random values between 0 and 0.5 and the second half with random values between 0.5 and 1.  Then time how long it takes to perform a comparison on the whole array with a threshold of 0.5. 
    So if the cause is branch prediction, the second array will threshold faster than the first as the branch prediction will be correct in all but 2 comparisons (at the start of the array and at the middle off the array).
    However, if the cause is the 64/32 bit suggestion, both arrays will threshold in the same amount of time.
    Well here are my results:
    On my PC there is no significant running time difference whether it is single our double precision. 
    There is a large difference though when I run the two same size arrays and compare them to 0.5 - the one with the first half containing random values smaller than 0.5 and the second half random values larger than 0.5 runs 25% faster than one with random values between 0 and 1.
    Thus my verdict - it is branch prediction that is the cause of the data-dependent running times. 

  • FEATURE REQUEST: use type literal for primitive StoredMap creation

    Mark, hello;
    I suggest to incorporate into api classes like shown below to avoid boiler plate with primitive bindings;
    the idea is to use TypeLiteral approach:
    http://google-guice.googlecode.com/svn/trunk/javadoc/com/google/inject/TypeLiteral.html
    so you can instantiate like this:
    // note the tail
              PrimitiveStoredMap<String, Integer> map = new PrimitiveStoredMap<String, Integer>(database) {};
    thank you;
    Andrei.
    import java.lang.reflect.Type;
    import java.util.HashMap;
    import java.util.Map;
    import com.sleepycat.bind.EntryBinding;
    import com.sleepycat.bind.tuple.BooleanBinding;
    import com.sleepycat.bind.tuple.ByteBinding;
    import com.sleepycat.bind.tuple.CharacterBinding;
    import com.sleepycat.bind.tuple.DoubleBinding;
    import com.sleepycat.bind.tuple.FloatBinding;
    import com.sleepycat.bind.tuple.IntegerBinding;
    import com.sleepycat.bind.tuple.LongBinding;
    import com.sleepycat.bind.tuple.ShortBinding;
    import com.sleepycat.bind.tuple.StringBinding;
    import com.sleepycat.bind.tuple.TupleBinding;
    import com.sleepycat.collections.StoredMap;
    import com.sleepycat.je.Database;
    public abstract class PrimitiveStoredMap<K, V> extends
              ConcurrentMapAdapter<K, V> {
         private static final Map<Class<?>, TupleBinding<?>> primitives = new HashMap<Class<?>, TupleBinding<?>>();
         static {
              addPrimitive(String.class, String.class, new StringBinding());
              addPrimitive(Character.class, Character.TYPE, new CharacterBinding());
              addPrimitive(Boolean.class, Boolean.TYPE, new BooleanBinding());
              addPrimitive(Byte.class, Byte.TYPE, new ByteBinding());
              addPrimitive(Short.class, Short.TYPE, new ShortBinding());
              addPrimitive(Integer.class, Integer.TYPE, new IntegerBinding());
              addPrimitive(Long.class, Long.TYPE, new LongBinding());
              addPrimitive(Float.class, Float.TYPE, new FloatBinding());
              addPrimitive(Double.class, Double.TYPE, new DoubleBinding());
         private static void addPrimitive(Class<?> cls1, Class<?> cls2,
                   TupleBinding<?> binding) {
              primitives.put(cls1, binding);
              primitives.put(cls2, binding);
         @SuppressWarnings("unchecked")
         public PrimitiveStoredMap(Database database) {
              ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
              Type[] typeArgs = type.getActualTypeArguments();
              Class<K> keyClass = (Class<K>) typeArgs[0];
              Class<V> valueClass = (Class<V>) typeArgs[1];
              TupleBinding<K> keyBinding = (TupleBinding<K>) primitives.get(keyClass);
              TupleBinding<V> valueBinding = (TupleBinding<V>) primitives.get(valueClass);
              if (keyBinding == null || valueBinding == null) {
                   throw new IllegalArgumentException(
                             "only string or primitive bindings "
                                       + "are supported for keys and values "
                                       + "you are using : (" + keyClass.getSimpleName()
                                       + "," + valueClass.getSimpleName() + ")");
              this.map = makeMap(database, keyBinding, valueBinding, true);
         protected StoredMap<K, V> makeMap(Database database,
                   EntryBinding<K> keyBinding, EntryBinding<V> valueBinding,
                   boolean isWriteable) {
              return new StoredMap<K, V>(//
                        database, keyBinding, valueBinding, isWriteable);
    import java.util.Collection;
    import java.util.Map;
    import java.util.Set;
    import java.util.concurrent.ConcurrentMap;
    public class ConcurrentMapAdapter<K, V> implements ConcurrentMap<K, V> {
         protected ConcurrentMap<K, V> map;
         @Override
         public int size() {
              return map.size();
         @Override
         public boolean isEmpty() {
              return map.isEmpty();
         @Override
         public boolean containsKey(Object key) {
              return map.containsKey(key);
         @Override
         public boolean containsValue(Object value) {
              return map.containsValue(value);
         @Override
         public V get(Object key) {
              return map.get(key);
         @Override
         public V put(K key, V value) {
              return map.put(key, value);
         @Override
         public V remove(Object key) {
              return map.remove(key);
         @Override
         public void putAll(Map<? extends K, ? extends V> m) {
              map.putAll(m);
         @Override
         public void clear() {
              map.clear();
         @Override
         public Set<K> keySet() {
              return map.keySet();
         @Override
         public Collection<V> values() {
              return map.values();
         @Override
         public Set<java.util.Map.Entry<K, V>> entrySet() {
              return map.entrySet();
         @Override
         public V putIfAbsent(K key, V value) {
              return map.putIfAbsent(key, value);
         @Override
         public boolean remove(Object key, Object value) {
              return map.remove(key, value);
         @Override
         public boolean replace(K key, V oldValue, V newValue) {
              return map.replace(key, oldValue, newValue);
         @Override
         public V replace(K key, V value) {
              return map.replace(key, value);
    Edited by: user8971924 on Mar 26, 2011 7:52 PM

    great! thanks for considering this;
    still more ideas: add the "byte array primitive":
    public class ByteArray {
         private final byte[] array;
         public ByteArray(final byte[] array) {
              this.array = array == null ? new byte[0] : array;
         public byte[] getArray() {
              return array;
         @Override
         public boolean equals(Object other) {
              if (other instanceof ByteArray) {
                   ByteArray that = (ByteArray) other;
                   return Arrays.equals(this.array, that.array);
              return false;
         private int hashCode;
         @Override
         public int hashCode() {
              if (hashCode == 0) {
                   hashCode = Arrays.hashCode(array);
              return hashCode;
         @Override
         public String toString() {
              return Arrays.toString(array);
    public class ByteArrayBinding extends TupleBinding<ByteArray> {
         @Override
         public ByteArray entryToObject(TupleInput ti) {
              return new ByteArray(ti.getBufferBytes().clone());
         @Override
         public void objectToEntry(ByteArray array, TupleOutput to) {
              to.write(array.getArray());
    public abstract class PrimitiveStoredMap<K, V> extends
              ConcurrentMapAdapter<K, V> {
         private static final Map<Class<?>, TupleBinding<?>> primitives = new HashMap<Class<?>, TupleBinding<?>>();
         static {
              // je
              addPrimitive(String.class, String.class, new StringBinding());
              addPrimitive(Character.class, Character.TYPE, new CharacterBinding());
              addPrimitive(Boolean.class, Boolean.TYPE, new BooleanBinding());
              addPrimitive(Byte.class, Byte.TYPE, new ByteBinding());
              addPrimitive(Short.class, Short.TYPE, new ShortBinding());
              addPrimitive(Integer.class, Integer.TYPE, new IntegerBinding());
              addPrimitive(Long.class, Long.TYPE, new LongBinding());
              addPrimitive(Float.class, Float.TYPE, new FloatBinding());
              addPrimitive(Double.class, Double.TYPE, new DoubleBinding());
              // custom
              addPrimitive(ByteArray.class, ByteArray.class, new ByteArrayBinding());
    }

  • Reg Mapping error cant produce the target element

    Hi gurus,
    I have a mapping requirement like
    sourceinput
    ||
    record
    ||
    Tab_id
    materialno
    condition type
    coustomergroup
    materialpricinggroup
    datefrom
    dateto
    uom
    amount
    in target side
    target input
    ||
    record----
    (0-1
    ||
    coustomergroup(1--unbound) if tab_id is R34
    ||
    Tab_ID
    coustomergroup
    UOM
    Materialno
    Materialpricinggroup(1--unbound) if the tab_id R346
    ||
    tab_id
    materialpricinggroup
    datefrom
    dateto
    based on the tab_id i need to create target node i.e if the tab_id is R345 then the fields which are under the node coustomer group
    will be populated
    if the tab_id is R346 then material pricing group node will populated
    i have tried like
    tab_id----
    | equalS--creatif--
    coustomergroup
    |
    constant(R345)----
    this mapping excute successfully if the occurence of the target node coustomergroup is 0---unbound
    if is 1----unbound the target gives error mapping exception
    my target structure is WSDL there giving as minoccurs=0 but while it is imported to xi it will come as 1---unbound
    please help out this
    let me know if anything is needed
    Edited by: katakoti on May 4, 2011 2:40 PM
    Edited by: katakoti on May 4, 2011 2:47 PM

    </xsd:sequence>
             </xsd:complexType>
             <xsd:complexType name="PRICING_MASTER_DATA">
                <xsd:sequence>
                   <xsd:element name="CUSTOMER_GRP" nillable="true" type="tns:ArrayOfCUSTOMER_GRP" minOccurs="0" />
                   <xsd:element name="SALES_ORG" nillable="true" type="tns:ArrayOfSALES_ORG" minOccurs="0" />
                   <xsd:element name="PRI_GRP" nillable="true" type="tns:ArrayOfPRI_GRP" minOccurs="0" />
                   <xsd:element name="MT_PRI_GRP" nillable="true" type="tns:ArrayOfMT_PRI_GRP" minOccurs="0" />
                   <xsd:element name="DIST_CHN" nillable="true" type="tns:ArrayOfDIST_CHN" minOccurs="0" />
                   <xsd:element name="INDUSTRIAL_CODE" nillable="true" type="tns:ArrayOfINDUSTRIAL_CODE" minOccurs="0" />
                   <xsd:element name="PRICING_TEMPLATES" nillable="true" type="tns:PRICING_TEMPLATES" minOccurs="0" />
                </xsd:sequence>
             </xsd:complexType>
             <xsd:complexType name="CUSTOMER_GRP">
                <xsd:sequence>
                   <xsd:element name="TABLE_ID" nillable="true" type="xsd:string" minOccurs="0" />
                   <xsd:element name="CUSTOMER_GROUP_NAME" nillable="true" type="xsd:string" minOccurs="0" />
                   <xsd:element name="CONDITION_DETAILS" nillable="true" type="tns:CONDITION_DETAILS" minOccurs="0" />
                   <xsd:element name="PRICING_DETAILS" nillable="true" type="tns:PRICING_DETAILS" minOccurs="0" />
                   <xsd:element name="BUSINESS_DETAILS" nillable="true" type="tns:BUSINESS_DETAILS" minOccurs="0" />
                </xsd:sequence>
             </xsd:complexType>
             <xsd:complexType name="CONDITION_DETAILS">
                <xsd:sequence>
                   <xsd:element name="CONDITION_TYPE_x0020_" nillable="true" type="xsd:string" minOccurs="0" />
                   <xsd:element name="VALID_DATE_FROM_x0020_" nillable="true" type="xsd:string" minOccurs="0" />
                   <xsd:element name="VALID_DATE_TO_x0020_" nillable="true" type="xsd:string" minOccurs="0" />
                </xsd:sequence>
             </xsd:complexType>
             <xsd:complexType name="PRICING_DETAILS">
                <xsd:sequence>
                   <xsd:element name="AMOUNT" nillable="true" type="xsd:string" minOccurs="0" />
                   <xsd:element name="RATE_UNIT" nillable="true" type="xsd:string" minOccurs="0" />
                   <xsd:element name="CONDITION_PRICING_UNIT" nillable="true" type="xsd:string" minOccurs="0" />
    from source side i wiil get the tab_id  based on that id. i need to populate the target node
    tab_id-=100  then coustomer_group
    tab_id = 200 then sal_org
    i got the source values like this
    tab_id     coustomer_group        sal_grp     pri_grp     condition_type   date_from     date_to          amount           rate_unit    
    100                c                                                                      c1             05/05/2011    06/05/2011   A                      R
    200                                                 s                                     c2              05/05/2011    06/05/2011   A1                    R1
    300                                                                 p                     c3              05/05/2001    06/05/2011   A3                    R3
    based on the tab_id i need to send the data to perticular node
    for this requirement i had follow the
    tab_id--
    -----------------------equalS-----------------creatif--------array of coustomer_group
    constant(100)
    its work fine when the arrayof coustomer_group is 0--unbound (i tried by creating the same target strucuture manually)
    it fails when the ocuurence is 1---unbound

Maybe you are looking for

  • ORA-01007 - variable not in select list error in pl\sql code

    Hi, When I tried to run this program I am getting below error: ORA-01007 - variable not in select list.Please help to resolve. Code: create or replace procedure "XX_BPM_DATA_P" (P_PROCESS_ID IN VARCHAR2) is TYPE l_entity_type IS TABLE OF xx_BPM_data.

  • White looks yellow/cream

    Hello HP and forum-members, I've got a question about the screen of the HP ENVY TouchSmart 15-j100ed.  White is not showed correctly, it looks more like cream/yellow. I've already updated the chipset and the drivers, re-installed all the drivers and

  • Select list filter in a tabular form problem

    Hello everyone: I need to filter a list in a tabular form, depend on another column value in the same row of the Tabular Form Try using the syntax *#COLUMN#* in the query of select list but did not work. This is my query SELECT   nombre_respuesta, co

  • Web service operation could not be found.

    Would CF give this error if there was simply an error in the cffunction code? The service is there and it looks fine. In fact, most of the code comes from another cffunction in the same file, but with more arguments and some additional code. I have c

  • Screen exit for ME32K

    Hi, In ME32k, My requirement is to remove email id field from Customer Data tab  in ME32K. Is there any exit or BADI available for this? Moderator Message: Did you make an effort to find out the right EXIT/BADI? Are you aware of some of the standard