Java Code Examples for java.util.Arrays#compare()

The following examples show how to use java.util.Arrays#compare() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CoinFromComparator.java    From nuls-v2 with MIT License 6 votes vote down vote up
@Override
public int compare(CoinFrom o1, CoinFrom o2) {
    if(!Arrays.equals(o1.getAddress(), o2.getAddress())){
        return AddressTool.getStringAddressByBytes(o1.getAddress()).compareTo(AddressTool.getStringAddressByBytes(o2.getAddress()));
    }else{
        if(o1.getAssetsChainId() != o2.getAssetsChainId()){
            return o1.getAssetsChainId() - o2.getAssetsChainId();
        }else{
            if(o1.getAssetsId() != o2.getAssetsId()){
                return o1.getAssetsId() - o2.getAssetsId();
            }else{
                if(!o1.getAmount().equals(o2.getAmount())){
                    return o1.getAmount().compareTo(o2.getAmount());
                }else{
                    return Arrays.compare(o1.getNonce(), o2.getNonce());
                }
            }
        }
    }
}
 
Example 2
Source File: Blake2bPersonalizationTest.java    From AVM with MIT License 6 votes vote down vote up
/**
 * Compare indices and ensure the intersection of hashes is empty
 *
 * @param a StepRow a
 * @param b StepRow b
 * @param len Number of elements to compare
 * @param lenIndices Number of indices to compare
 * @return true if distinct; false otherwise
 * @throws NullPointerException when given null input
 */
private boolean distinctIndices(FullStepRow a, FullStepRow b, int len, int lenIndices) {
    if (a == null || b == null) {
        throw new NullPointerException("null FullStepRow passed");
    }

    for (int i = 0; i < lenIndices; i = i + Integer.BYTES) {
        for (int j = 0; j < lenIndices; j = j + Integer.BYTES) {
            if (Arrays.compare(
                    Arrays.copyOfRange(a.getHash(), len + i, len + i + Integer.BYTES),
                    Arrays.copyOfRange(b.getHash(), len + j, len + j + Integer.BYTES))
                    == 0) {
                return false;
            }
        }
    }
    return true;
}
 
Example 3
Source File: EquiValidator.java    From aion with MIT License 6 votes vote down vote up
/**
 * Compare indices and ensure the intersection of hashes is empty
 *
 * @param a StepRow a
 * @param b StepRow b
 * @param len Number of elements to compare
 * @param lenIndices Number of indices to compare
 * @return true if distinct; false otherwise
 * @throws NullPointerException when given null input
 */
private boolean distinctIndices(FullStepRow a, FullStepRow b, int len, int lenIndices) {
    if (a == null || b == null) {
        throw new NullPointerException("null FullStepRow passed");
    }

    for (int i = 0; i < lenIndices; i = i + Integer.BYTES) {
        for (int j = 0; j < lenIndices; j = j + Integer.BYTES) {
            if (Arrays.compare(
                            Arrays.copyOfRange(a.getHash(), len + i, len + i + Integer.BYTES),
                            Arrays.copyOfRange(b.getHash(), len + j, len + j + Integer.BYTES))
                    == 0) {
                return false;
            }
        }
    }
    return true;
}
 
Example 4
Source File: Hash256.java    From aion with MIT License 5 votes vote down vote up
@Override
public boolean equals(Object other) {
    if (!(other instanceof Hash256)) {
        return false;
    } else {
        byte[] otherAddress = ((Hash256) other).toBytes();
        return Arrays.compare(this.hash, otherAddress) == 0;
    }
}
 
Example 5
Source File: ModuleDescriptor.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Compares two sets of {@code Comparable} objects.
 */
@SuppressWarnings("unchecked")
private static <T extends Object & Comparable<? super T>>
int compare(Set<T> s1, Set<T> s2) {
    T[] a1 = (T[]) s1.toArray();
    T[] a2 = (T[]) s2.toArray();
    Arrays.sort(a1);
    Arrays.sort(a2);
    return Arrays.compare(a1, a2);
}
 
Example 6
Source File: ModuleDescriptor.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Compares two sets of {@code Comparable} objects.
 */
@SuppressWarnings("unchecked")
private static <T extends Object & Comparable<? super T>>
int compare(Set<T> s1, Set<T> s2) {
    T[] a1 = (T[]) s1.toArray();
    T[] a2 = (T[]) s2.toArray();
    Arrays.sort(a1);
    Arrays.sort(a2);
    return Arrays.compare(a1, a2);
}
 
Example 7
Source File: AionHub.java    From aion with MIT License 5 votes vote down vote up
TransactionSortedSet() {
    super(
        (tx1, tx2) -> {
            long nonceDiff =
                ByteUtil.byteArrayToLong(tx1.getNonce())
                    - ByteUtil.byteArrayToLong(tx2.getNonce());

            if (nonceDiff != 0) {
                return nonceDiff > 0 ? 1 : -1;
            }
            return Arrays.compare(tx1.getTransactionHash(), tx2.getTransactionHash());
        });
}
 
Example 8
Source File: ApiWeb3Aion.java    From aion with MIT License 5 votes vote down vote up
/**
 * This function runs as fast as is possible with the on-disk data model Use this to retrieve
 * the Transaction Receipt if you know the block hash already
 */
public RpcMsg ops_getTransactionReceiptByTransactionAndBlockHash(Object _params) {
    String _transactionHash;
    String _blockHash;
    if (_params instanceof JSONArray) {
        _transactionHash = ((JSONArray) _params).get(0) + "";
        _blockHash = ((JSONArray) _params).get(1) + "";
    } else if (_params instanceof JSONObject) {
        _transactionHash = ((JSONObject) _params).get("transactionHash") + "";
        _blockHash = ((JSONObject) _params).get("blockHash") + "";
    } else {
        return new RpcMsg(null, RpcError.INVALID_PARAMS, "Invalid parameters");
    }

    byte[] transactionHash = StringUtils.StringHexToByteArray(_transactionHash);
    byte[] blockHash = StringUtils.StringHexToByteArray(_blockHash);

    // cast will cause issues after the PoW refactor goes in
    AionBlockchainImpl chain = (AionBlockchainImpl) this.ac.getAionHub().getBlockchain();

    AionTxInfo info = chain.getTransactionInfoLite(transactionHash, blockHash);
    if (info == null) {
        return new RpcMsg(JSONObject.NULL);
    }

    Block block = blockCache.get(ByteArrayWrapper.wrap(blockHash));

    AionTransaction t = block.getTransactionsList().get(info.getIndex());
    if (Arrays.compare(t.getTransactionHash(), transactionHash) != 0) {
        LOG.error("INCONSISTENT STATE: transaction info's transaction index is wrong.");
        return new RpcMsg(null, RpcError.INTERNAL_ERROR, "Database Error");
    }
    info.setTransaction(t);

    return new RpcMsg((new TxRecpt(block, info, 0L, true)).toJson());
}
 
Example 9
Source File: ByteUtilExtendTest.java    From aion with MIT License 5 votes vote down vote up
/** Compares two regions of byte array. */
public static int compareTo(
        byte[] array1, int offset1, int size1, byte[] array2, int offset2, int size2) {
    byte[] b1 = Arrays.copyOfRange(array1, offset1, offset1 + size1);
    byte[] b2 = Arrays.copyOfRange(array2, offset2, offset2 + size2);

    return Arrays.compare(b1, b2);
}
 
Example 10
Source File: ByteArrayWrapper.java    From aion with MIT License 4 votes vote down vote up
@Override
public int compareTo(ByteArrayWrapper o) {
    // do not use getter here to avoid performance loss due to cloning
    return Arrays.compare(this.bytes, o.bytes);
}
 
Example 11
Source File: ByteArrayWrapper.java    From aion with MIT License 4 votes vote down vote up
@Override
public int compareTo(ByteArrayWrapper o) {
    // do not use getter here to avoid performance loss due to cloning
    return Arrays.compare(this.bytes, o.bytes);
}
 
Example 12
Source File: FireDisplay.java    From DrivenByMoss with GNU Lesser General Public License v3.0 4 votes vote down vote up
/** {@inheritDoc} */
@Override
protected void send (final IBitmap image)
{
    synchronized (this.data)
    {
        image.encode ( (imageBuffer, width, height) -> {

            // Unwind 128x64 arrangement into a 1024x8 arrangement of pixels
            for (int stripe = 0; stripe < 8; stripe++)
            {
                for (int y = 0; y < height / 8; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        final int blue = imageBuffer.get ();
                        final int green = imageBuffer.get ();
                        final int red = imageBuffer.get ();
                        imageBuffer.get (); // Drop unused Alpha

                        final int xpos = x + 128 * (y / 8);
                        final int ypos = y % 8;

                        // Remap by tiling 7x8 block of translated pixels
                        final int remapBit = BIT_MUTATE[ypos][xpos % 7];
                        final int idx = xpos / 7 * 8 + remapBit / 7;
                        if (blue + green + red < 0)
                            this.oledBitmap[stripe][idx] |= 1 << remapBit % 7;
                        else
                            this.oledBitmap[stripe][idx] &= ~(1 << remapBit % 7);
                    }
                }
            }
        });

        // Convert to sysex and send to device
        for (int stripe = 0; stripe < 8; stripe++)
        {
            // Start 8-pixel band of update
            this.data[7] = (byte) stripe;
            // End 8-pixel band of update (here, 8 bands of 8 pixels, i.e. the whole display)
            this.data[8] = (byte) stripe;

            for (int i = 0; i < STRIPE_SIZE; i++)
                this.data[11 + i] = (byte) this.oledBitmap[stripe][i];

            // Slow down display updates to not flood the device controller
            // Send if content has change or every 3 seconds if there was no change to keep
            // the display from going into sleep mode
            final long now = System.currentTimeMillis ();
            if (Arrays.compare (this.oledBitmap[stripe], this.oldOledBitmap[stripe]) == 0 && now - this.lastSend < 3000)
                continue;
            System.arraycopy (this.oledBitmap[stripe], 0, this.oldOledBitmap[stripe], 0, STRIPE_SIZE);
            this.lastSend = now;

            this.output.sendSysex (this.data);
        }
    }
}
 
Example 13
Source File: Main.java    From Java-Coding-Problems with MIT License 4 votes vote down vote up
public static void main(String[] args) {

        // arrays of integers
        int[] integers1 = new int[]{3, 4, 5, 6, 1, 5};
        int[] integers2 = new int[]{3, 4, 5, 6, 1, 5};
        int[] integers3 = new int[]{3, 4, 5, 6, 1, 3};

        // arrays of melons
        Melon[] melons1 = new Melon[]{new Melon("Horned", 1500), new Melon("Gac", 1000)};
        Melon[] melons2 = new Melon[]{new Melon("Horned", 1500), new Melon("Gac", 1000)};
        Melon[] melons3 = new Melon[]{new Melon("Hami", 1600), new Melon("Gac", 800)};

        // Comparators
        Comparator<Melon> byType = Comparator.comparing(Melon::getType);

        System.out.println("compare:\n-------\n");
        System.out.println("Interpreting return:\n"
                + "  - 0 if the first and second array are equal and contain the same elements in the same order;\n"
                + "  - a value less than 0 if the first array is lexicographically less than the second array;\n"
                + "  - a value greater than 0 if the first array is lexicographically greater than the second array\n");

        int i12 = Arrays.compare(integers1, integers2);
        System.out.println("integers1 compared lexicographically with integers2 returned: " + i12);

        int i13 = Arrays.compare(integers1, integers3);
        System.out.println("integers1 compared lexicographically with integers3 returned: " + i13);

        int is13 = Arrays.compare(integers1, 3, 6, integers3, 3, 6);
        System.out.println("integers1 compared lexicographically with integers3 in range [3,6) returned: " + is13);

        @SuppressWarnings("unchecked")
        int m12 = Arrays.compare(melons1, melons2);
        System.out.println("melons1 compared lexicographically with melons2 returned: " + m12);

        @SuppressWarnings("unchecked")
        int m13 = Arrays.compare(melons1, melons3);
        System.out.println("melons1 compared lexicographically with melons3 returned: " + m13);

        @SuppressWarnings("unchecked")
        int ms13 = Arrays.compare(melons1, 1, 2, melons3, 1, 2);
        System.out.println("melons1 compared lexicographically with melons3 in range [1, 2) returned: " + ms13);

        int mt13 = Arrays.compare(melons1, melons3, byType);
        System.out.println("melons1 compared lexicographically with melons3 by type returned: " + mt13);
        
        int mrt13 = Arrays.compare(melons1, 1, 2, melons3, 1, 2, byType);
        System.out.println("melons1 compared lexicographically with melons3 by type in range [1,2) returned: " + mrt13);
    }
 
Example 14
Source File: IntsRef.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
/** Signed int order comparison */
@Override
public int compareTo(IntsRef other) {
  return Arrays.compare(this.ints, this.offset, this.offset + this.length, 
                              other.ints, other.offset, other.offset + other.length);
}
 
Example 15
Source File: LongsRef.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
/** Signed int order comparison */
@Override
public int compareTo(LongsRef other) {
  return Arrays.compare(this.longs, this.offset, this.offset + this.length, 
                              other.longs, other.offset, other.offset + other.length);
}
 
Example 16
Source File: CharsRef.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
/** Signed int order comparison */
@Override
public int compareTo(CharsRef other) {
  return Arrays.compare(this.chars, this.offset, this.offset + this.length, 
                              other.chars, other.offset, other.offset + other.length);
}
 
Example 17
Source File: Hash256.java    From aion with MIT License 2 votes vote down vote up
/**
 * Compares this object with the specified object for order. Returns a negative integer, zero,
 * or a positive integer as this object is less than, equal to, or greater than the specified
 * object.
 *
 * <p>
 *
 * <p>The implementor must ensure {@code sgn(x.compareTo(y)) == -sgn(y.compareTo(x))} for all
 * {@code x} and {@code y}. (This implies that {@code x.compareTo(y)} must throw an exception
 * iff {@code y.compareTo(x)} throws an exception.)
 *
 * <p>
 *
 * <p>The implementor must also ensure that the relation is transitive: {@code (x.compareTo(y) >
 * 0 && y.compareTo(z) > 0)} implies {@code x.compareTo(z) > 0}.
 *
 * <p>
 *
 * <p>Finally, the implementor must ensure that {@code x.compareTo(y)==0} implies that {@code
 * sgn(x.compareTo(z)) == sgn(y.compareTo(z))}, for all {@code z}.
 *
 * <p>
 *
 * <p>It is strongly recommended, but <i>not</i> strictly required that {@code
 * (x.compareTo(y)==0) == (x.equals(y))}. Generally speaking, any class that implements the
 * {@code Comparable} interface and violates this condition should clearly indicate this fact.
 * The recommended language is "Note: this class has a natural ordering that is inconsistent
 * with equals."
 *
 * <p>
 *
 * <p>In the foregoing description, the notation {@code sgn(}<i>expression</i>{@code )}
 * designates the mathematical <i>signum</i> function, which is defined to return one of {@code
 * -1}, {@code 0}, or {@code 1} according to whether the value of <i>expression</i> is negative,
 * zero, or positive, respectively.
 *
 * @param o the object to be compared.
 * @return a negative integer, zero, or a positive integer as this object is less than, equal
 *     to, or greater than the specified object.
 * @throws NullPointerException if the specified object is null
 * @throws ClassCastException if the specified object's type prevents it from being compared to
 *     this object.
 */
@Override
public int compareTo(Hash256 o) {
    return Arrays.compare(this.hash, o.toBytes());
}