Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2008 The Guava Authors
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   * http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 
 package com.google.common.primitives;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkElementIndex;
 import static com.google.common.base.Preconditions.checkNotNull;
 import static com.google.common.base.Preconditions.checkPositionIndexes;
 
 
 import java.util.List;
Static utility methods pertaining to long primitives, that are not already found in either java.lang.Long or java.util.Arrays.

See the Guava User Guide article on primitive utilities.

Author(s):
Kevin Bourrillion
Since:
1.0
 
 public final class Longs {
   private Longs() {}

  
The number of bytes required to represent a primitive long value.
 
   public static final int BYTES = . / .;

  
The largest power of two that can be represented as a long.

Since:
10.0
 
   public static final long MAX_POWER_OF_TWO = 1L << (. - 2);

  
Returns a hash code for value; equal to the result of invoking ((Long) value).hashCode().

This method always return the value specified by java.lang.Long.hashCode() in java, which might be different from ((Long) value).hashCode() in GWT because java.lang.Long.hashCode() in GWT does not obey the JRE contract.

Parameters:
value a primitive long value
Returns:
a hash code for the value
 
   public static int hashCode(long value) {
     return (int) (value ^ (value >>> 32));
   }

  
Compares the two specified long values. The sign of the value returned is the same as that of ((Long) a).compareTo(b).

Parameters:
a the first long to compare
b the second long to compare
Returns:
a negative value if a is less than b; a positive value if a is greater than b; or zero if they are equal
 
   public static int compare(long along b) {
     return (a < b) ? -1 : ((a > b) ? 1 : 0);
   }

  
Returns true if target is present as an element anywhere in array.

Parameters:
array an array of long values, possibly empty
target a primitive long value
Returns:
true if array[i] == target for some value of i
  public static boolean contains(long[] arraylong target) {
    for (long value : array) {
      if (value == target) {
        return true;
      }
    }
    return false;
  }

  
Returns the index of the first appearance of the value target in array.

Parameters:
array an array of long values, possibly empty
target a primitive long value
Returns:
the least index i for which array[i] == target, or -1 if no such index exists.
  public static int indexOf(long[] arraylong target) {
    return indexOf(arraytarget, 0, array.length);
  }
  // TODO(kevinb): consider making this public
  private static int indexOf(
      long[] arraylong targetint startint end) {
    for (int i = starti < endi++) {
      if (array[i] == target) {
        return i;
      }
    }
    return -1;
  }

  
Returns the start position of the first occurrence of the specified target within array, or -1 if there is no such occurrence.

More formally, returns the lowest index i such that java.util.Arrays.copyOfRange(array, i, i + target.length) contains exactly the same elements as target.

Parameters:
array the array to search for the sequence target
target the array to search for as a sub-sequence of array
  public static int indexOf(long[] arraylong[] target) {
    checkNotNull(array"array");
    checkNotNull(target"target");
    if (target.length == 0) {
      return 0;
    }
    outer:
    for (int i = 0; i < array.length - target.length + 1; i++) {
      for (int j = 0; j < target.lengthj++) {
        if (array[i + j] != target[j]) {
          continue outer;
        }
      }
      return i;
    }
    return -1;
  }

  
Returns the index of the last appearance of the value target in array.

Parameters:
array an array of long values, possibly empty
target a primitive long value
Returns:
the greatest index i for which array[i] == target, or -1 if no such index exists.
  public static int lastIndexOf(long[] arraylong target) {
    return lastIndexOf(arraytarget, 0, array.length);
  }
  // TODO(kevinb): consider making this public
  private static int lastIndexOf(
      long[] arraylong targetint startint end) {
    for (int i = end - 1; i >= starti--) {
      if (array[i] == target) {
        return i;
      }
    }
    return -1;
  }

  
Returns the least value present in array.

Parameters:
array a nonempty array of long values
Returns:
the value present in array that is less than or equal to every other value in the array
Throws:
java.lang.IllegalArgumentException if array is empty
  public static long min(long... array) {
    checkArgument(array.length > 0);
    long min = array[0];
    for (int i = 1; i < array.lengthi++) {
      if (array[i] < min) {
        min = array[i];
      }
    }
    return min;
  }

  
Returns the greatest value present in array.

Parameters:
array a nonempty array of long values
Returns:
the value present in array that is greater than or equal to every other value in the array
Throws:
java.lang.IllegalArgumentException if array is empty
  public static long max(long... array) {
    checkArgument(array.length > 0);
    long max = array[0];
    for (int i = 1; i < array.lengthi++) {
      if (array[i] > max) {
        max = array[i];
      }
    }
    return max;
  }

  
Returns the values from each provided array combined into a single array. For example, concat(new long[] {a, b, new long[] {}, new long[] {c}} returns the array {a, b, c}.

Parameters:
arrays zero or more long arrays
Returns:
a single array containing all the values from the source arrays, in order
  public static long[] concat(long[]... arrays) {
    int length = 0;
    for (long[] array : arrays) {
      length += array.length;
    }
    long[] result = new long[length];
    int pos = 0;
    for (long[] array : arrays) {
      System.arraycopy(array, 0, resultposarray.length);
      pos += array.length;
    }
    return result;
  }

  
Returns a big-endian representation of value in an 8-element byte array; equivalent to ByteBuffer.allocate(8).putLong(value).array(). For example, the input value 0x1213141516171819L would yield the byte array {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}.

If you need to convert and concatenate several values (possibly even of different types), use a shared java.nio.ByteBuffer instance, or use com.google.common.io.ByteStreams.newDataOutput() to get a growable buffer.

  public static byte[] toByteArray(long value) {
    // Note that this code needs to stay compatible with GWT, which has known
    // bugs when narrowing byte casts of long values occur.
    byte[] result = new byte[8];
    for (int i = 7; i >= 0; i--) {
      result[i] = (byte) (value & 0xffL);
      value >>= 8;
    }
    return result;
  }

  
Returns the long value whose big-endian representation is stored in the first 8 bytes of bytes; equivalent to ByteBuffer.wrap(bytes).getLong(). For example, the input byte array {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19} would yield the long value 0x1213141516171819L.

Arguably, it's preferable to use java.nio.ByteBuffer; that library exposes much more flexibility at little cost in readability.

Throws:
java.lang.IllegalArgumentException if bytes has fewer than 8 elements
  public static long fromByteArray(byte[] bytes) {
    checkArgument(bytes.length >= ,
        "array too small: %s < %s"bytes.length);
    return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3],
        bytes[4], bytes[5], bytes[6], bytes[7]) ;
  }

  
Returns the long value whose byte representation is the given 8 bytes, in big-endian order; equivalent to Longs.fromByteArray(new byte[] {b1, b2, b3, b4, b5, b6, b7, b8)}.

Since:
7.0
  public static long fromBytes(byte b1byte b2byte b3byte b4,
      byte b5byte b6byte b7byte b8) {
    return (b1 & 0xFFL) << 56
        | (b2 & 0xFFL) << 48
        | (b3 & 0xFFL) << 40
        | (b4 & 0xFFL) << 32
        | (b5 & 0xFFL) << 24
        | (b6 & 0xFFL) << 16
        | (b7 & 0xFFL) << 8
        | (b8 & 0xFFL);
  }

  
Parses the specified string as a signed decimal long value. The ASCII character '-' ('\u002D') is recognized as the minus sign.

Unlike java.lang.Long.parseLong(java.lang.String), this method returns null instead of throwing an exception if parsing fails.

Note that strings prefixed with ASCII '+' are rejected, even under JDK 7, despite the change to java.lang.Long.parseLong(java.lang.String) for that version.

Parameters:
string the string representation of a long value
Returns:
the long value represented by string, or null if string has a length of zero or cannot be parsed as a long value
Since:
14.0
  @Beta
  public static Long tryParse(String string) {
    if (checkNotNull(string).isEmpty()) {
      return null;
    }
    boolean negative = string.charAt(0) == '-';
    int index = negative ? 1 : 0;
    if (index == string.length()) {
      return null;
    }
    int digit = string.charAt(index++) - '0';
    if (digit < 0 || digit > 9) {
      return null;
    }
    long accum = -digit;
    while (index < string.length()) {
      digit = string.charAt(index++) - '0';
      if (digit < 0 || digit > 9 || accum < . / 10) {
        return null;
      }
      accum *= 10;
      if (accum < . + digit) {
        return null;
      }
      accum -= digit;
    }
    if (negative) {
      return accum;
    } else if (accum == .) {
      return null;
    } else {
      return -accum;
    }
  }

  
Returns an array containing the same values as array, but guaranteed to be of a specified minimum length. If array already has a length of at least minLength, it is returned directly. Otherwise, a new array of size minLength + padding is returned, containing the values of array, and zeroes in the remaining places.

Parameters:
array the source array
minLength the minimum length the returned array must guarantee
padding an extra amount to "grow" the array by if growth is necessary
Returns:
an array containing the values of array, with guaranteed minimum length minLength
Throws:
java.lang.IllegalArgumentException if minLength or padding is negative
  public static long[] ensureCapacity(
      long[] arrayint minLengthint padding) {
    checkArgument(minLength >= 0, "Invalid minLength: %s"minLength);
    checkArgument(padding >= 0, "Invalid padding: %s"padding);
    return (array.length < minLength)
        ? copyOf(arrayminLength + padding)
        : array;
  }
  // Arrays.copyOf() requires Java 6
  private static long[] copyOf(long[] originalint length) {
    long[] copy = new long[length];
    System.arraycopy(original, 0, copy, 0, Math.min(original.lengthlength));
    return copy;
  }

  
Returns a string containing the supplied long values separated by separator. For example, join("-", 1L, 2L, 3L) returns the string "1-2-3".

Parameters:
separator the text that should appear between consecutive values in the resulting string (but not at the start or end)
array an array of long values, possibly empty
  public static String join(String separatorlong... array) {
    checkNotNull(separator);
    if (array.length == 0) {
      return "";
    }
    // For pre-sizing a builder, just get the right order of magnitude
    StringBuilder builder = new StringBuilder(array.length * 10);
    builder.append(array[0]);
    for (int i = 1; i < array.lengthi++) {
      builder.append(separator).append(array[i]);
    }
    return builder.toString();
  }

  
Returns a comparator that compares two long arrays lexicographically. That is, it compares, using compare(long,long)), the first pair of values that follow any common prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For example, [] < [1L] < [1L, 2L] < [2L].

The returned comparator is inconsistent with java.lang.Object.equals(java.lang.Object) (since arrays support only identity equality), but it is consistent with java.util.Arrays.equals(long[],long[]).

Since:
2.0
See also:
Lexicographical order article at Wikipedia
  public static Comparator<long[]> lexicographicalComparator() {
  }
  private enum LexicographicalComparator implements Comparator<long[]> {
    INSTANCE;
    @Override
    public int compare(long[] leftlong[] right) {
      int minLength = Math.min(left.lengthright.length);
      for (int i = 0; i < minLengthi++) {
        int result = Longs.compare(left[i], right[i]);
        if (result != 0) {
          return result;
        }
      }
      return left.length - right.length;
    }
  }

  
Returns an array containing each value of collection, converted to a long value in the manner of java.lang.Number.longValue().

Elements are copied from the argument collection as if by collection.toArray(). Calling this method is as thread-safe as calling that method.

Parameters:
collection a collection of Number instances
Returns:
an array containing the same values as collection, in the same order, converted to primitives
Throws:
java.lang.NullPointerException if collection or any of its elements is null
Since:
1.0 (parameter was Collection<Long> before 12.0)
  public static long[] toArray(Collection<? extends Numbercollection) {
    if (collection instanceof LongArrayAsList) {
      return ((LongArrayAsListcollection).toLongArray();
    }
    Object[] boxedArray = collection.toArray();
    int len = boxedArray.length;
    long[] array = new long[len];
    for (int i = 0; i < leni++) {
      // checkNotNull for GWT (do not optimize)
      array[i] = ((NumbercheckNotNull(boxedArray[i])).longValue();
    }
    return array;
  }

  
Returns a fixed-size list backed by the specified array, similar to java.util.Arrays.asList(java.lang.Object[]). The list supports java.util.List.set(int,java.lang.Object), but any attempt to set a value to null will result in a java.lang.NullPointerException.

The returned list maintains the values, but not the identities, of Long objects written to or read from it. For example, whether list.get(0) == list.get(0) is true for the returned list is unspecified.

Parameters:
backingArray the array to back the list
Returns:
a list view of the array
  public static List<LongasList(long... backingArray) {
    if (backingArray.length == 0) {
      return Collections.emptyList();
    }
    return new LongArrayAsList(backingArray);
  }
  private static class LongArrayAsList extends AbstractList<Long>
      implements RandomAccessSerializable {
    final long[] array;
    final int start;
    final int end;
    LongArrayAsList(long[] array) {
      this(array, 0, array.length);
    }
    LongArrayAsList(long[] arrayint startint end) {
      this. = array;
      this. = start;
      this. = end;
    }
    @Override public int size() {
      return  - ;
    }
    @Override public boolean isEmpty() {
      return false;
    }
    @Override public Long get(int index) {
      checkElementIndex(indexsize());
      return [ + index];
    }
    @Override public boolean contains(Object target) {
      // Overridden to prevent a ton of boxing
      return (target instanceof Long)
          && Longs.indexOf(, (Longtarget) != -1;
    }
    @Override public int indexOf(Object target) {
      // Overridden to prevent a ton of boxing
      if (target instanceof Long) {
        int i = Longs.indexOf(, (Longtarget);
        if (i >= 0) {
          return i - ;
        }
      }
      return -1;
    }
    @Override public int lastIndexOf(Object target) {
      // Overridden to prevent a ton of boxing
      if (target instanceof Long) {
        int i = Longs.lastIndexOf(, (Longtarget);
        if (i >= 0) {
          return i - ;
        }
      }
      return -1;
    }
    @Override public Long set(int indexLong element) {
      checkElementIndex(indexsize());
      long oldValue = [ + index];
      // checkNotNull for GWT (do not optimize)
      [ + index] = checkNotNull(element);
      return oldValue;
    }
    @Override public List<LongsubList(int fromIndexint toIndex) {
      int size = size();
      checkPositionIndexes(fromIndextoIndexsize);
      if (fromIndex == toIndex) {
        return Collections.emptyList();
      }
      return new LongArrayAsList( + fromIndex + toIndex);
    }
    @Override public boolean equals(Object object) {
      if (object == this) {
        return true;
      }
      if (object instanceof LongArrayAsList) {
        LongArrayAsList that = (LongArrayAsListobject;
        int size = size();
        if (that.size() != size) {
          return false;
        }
        for (int i = 0; i < sizei++) {
          if ([ + i] != that.array[that.start + i]) {
            return false;
          }
        }
        return true;
      }
      return super.equals(object);
    }
    @Override public int hashCode() {
      int result = 1;
      for (int i = i < i++) {
        result = 31 * result + Longs.hashCode([i]);
      }
      return result;
    }
    @Override public String toString() {
      StringBuilder builder = new StringBuilder(size() * 10);
      builder.append('[').append([]);
      for (int i =  + 1; i < i++) {
        builder.append(", ").append([i]);
      }
      return builder.append(']').toString();
    }
    long[] toLongArray() {
      // Arrays.copyOfRange() is not available under GWT
      int size = size();
      long[] result = new long[size];
      System.arraycopy(result, 0, size);
      return result;
    }
    private static final long serialVersionUID = 0;
  }
New to GrepCode? Check out our FAQ X