Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2007 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.base;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
 import java.util.List;
 
Helper functions that can operate on any Object.

See the Guava User Guide on writing Object methods with Objects.

Author(s):
Laurence Gonsalves
Since:
2.0 (imported from Google Collections Library)
 
 public final class Objects {
   private Objects() {}

  
Determines whether two possibly-null objects are equal. Returns:

This assumes that any non-null objects passed to this function conform to the equals() contract.

 
   public static boolean equal(@Nullable Object a, @Nullable Object b) {
     return a == b || (a != null && a.equals(b));
   }

  
Generates a hash code for multiple values. The hash code is generated by calling java.util.Arrays.hashCode(java.lang.Object[]).

This is useful for implementing java.lang.Object.hashCode(). For example, in an object that has three properties, x, y, and z, one could write:

 public int hashCode() {
   return Objects.hashCode(getX(), getY(), getZ());
 }
Warning: When a single object is supplied, the returned hash code does not equal the hash code of that object.
 
   public static int hashCode(@Nullable Object... objects) {
     return Arrays.hashCode(objects);
   }

  
Creates an instance of Objects.ToStringHelper.

This is helpful for implementing java.lang.Object.toString(). Specification by example:

   // Returns "ClassName{"
   Objects.toStringHelper(this)
       .toString();

   // Returns "ClassName{x=1}"
   Objects.toStringHelper(this)
       .add("x", 1)
       .toString();

   // Returns "MyObject{x=1}"
   Objects.toStringHelper("MyObject")
       .add("x", 1)
       .toString();

   // Returns "ClassName{x=1, y=foo}"
   Objects.toStringHelper(this)
       .add("x", 1)
       .add("y", "foo")
       .toString();
   }}

   // Returns "ClassName{x=1}"
   Objects.toStringHelper(this)
       .omitNullValues()
       .add("x", 1)
       .add("y", null)
       .toString();
   }}

Note that in GWT, class names are often obfuscated.

Parameters:
self the object to generate the string for (typically this), used only for its class name
Since:
2.0
  public static ToStringHelper toStringHelper(Object self) {
    return new ToStringHelper(simpleName(self.getClass()));
  }

  
Creates an instance of Objects.ToStringHelper in the same manner as toStringHelper(java.lang.Object), but using the name of clazz instead of using an instance's java.lang.Object.getClass().

Note that in GWT, class names are often obfuscated.

Parameters:
clazz the java.lang.Class of the instance
Since:
7.0 (source-compatible since 2.0)
  public static ToStringHelper toStringHelper(Class<?> clazz) {
    return new ToStringHelper(simpleName(clazz));
  }

  
Creates an instance of Objects.ToStringHelper in the same manner as toStringHelper(java.lang.Object), but using className instead of using an instance's java.lang.Object.getClass().

Parameters:
className the name of the instance type
Since:
7.0 (source-compatible since 2.0)
  public static ToStringHelper toStringHelper(String className) {
    return new ToStringHelper(className);
  }

  
java.lang.Class.getSimpleName() is not GWT compatible yet, so we provide our own implementation.
  private static String simpleName(Class<?> clazz) {
    String name = clazz.getName();
    // the nth anonymous class has a class name ending in "Outer$n"
    // and local inner classes have names ending in "Outer.$1Inner"
    name = name.replaceAll("\\$[0-9]+""\\$");
    // we want the name of the inner class all by its lonesome
    int start = name.lastIndexOf('$');
    // if this isn't an inner class, just find the start of the
    // top level class name.
    if (start == -1) {
      start = name.lastIndexOf('.');
    }
    return name.substring(start + 1);
  }

  
Returns the first of two given parameters that is not null, if either is, or otherwise throws a java.lang.NullPointerException.

Note: if first is represented as an Optional<T>, this can be accomplished with first.or(second). That approach also allows for lazy evaluation of the fallback instance, using first.or(Supplier).

Returns:
first if first is not null, or second if first is null and second is not null
Throws:
java.lang.NullPointerException if both first and second were null
Since:
3.0
  public static <T> T firstNonNull(@Nullable T first, @Nullable T second) {
    return first != null ? first : checkNotNull(second);
  }

  
Support class for Objects.toStringHelper(java.lang.Object).

Author(s):
Jason Lee
Since:
2.0
  public static final class ToStringHelper {
    private final String className;
    private final List<ValueHoldervalueHolders =
        new LinkedList<ValueHolder>();
    private boolean omitNullValues = false;

    
Use Objects.toStringHelper(java.lang.Object) to create an instance.
    private ToStringHelper(String className) {
      this. = checkNotNull(className);
    }

    
When called, the formatted output returned by toString() will ignore null values.

Since:
12.0
    @Beta
    public ToStringHelper omitNullValues() {
       = true;
      return this;
    }

    
Adds a name/value pair to the formatted output in name=value format. If value is null, the string "null" is used, unless omitNullValues() is called, in which case this name/value pair will not be added.
    public ToStringHelper add(String name, @Nullable Object value) {
      checkNotNull(name);
      addHolder(value)..append(name).append('=').append(value);
      return this;
    }

    
Adds a name/value pair to the formatted output in name=value format.

Since:
11.0 (source-compatible since 2.0)
    public ToStringHelper add(String nameboolean value) {
      checkNameAndAppend(name).append(value);
      return this;
    }

    
Adds a name/value pair to the formatted output in name=value format.

Since:
11.0 (source-compatible since 2.0)
    public ToStringHelper add(String namechar value) {
      checkNameAndAppend(name).append(value);
      return this;
    }

    
Adds a name/value pair to the formatted output in name=value format.

Since:
11.0 (source-compatible since 2.0)
    public ToStringHelper add(String namedouble value) {
      checkNameAndAppend(name).append(value);
      return this;
    }

    
Adds a name/value pair to the formatted output in name=value format.

Since:
11.0 (source-compatible since 2.0)
    public ToStringHelper add(String namefloat value) {
      checkNameAndAppend(name).append(value);
      return this;
    }

    
Adds a name/value pair to the formatted output in name=value format.

Since:
11.0 (source-compatible since 2.0)
    public ToStringHelper add(String nameint value) {
      checkNameAndAppend(name).append(value);
      return this;
    }

    
Adds a name/value pair to the formatted output in name=value format.

Since:
11.0 (source-compatible since 2.0)
    public ToStringHelper add(String namelong value) {
      checkNameAndAppend(name).append(value);
      return this;
    }
    private StringBuilder checkNameAndAppend(String name) {
      checkNotNull(name);
      return addHolder()..append(name).append('=');
    }

    
Adds an unnamed value to the formatted output.

It is strongly encouraged to use add(java.lang.String,java.lang.Object) instead and give value a readable name.

    public ToStringHelper addValue(@Nullable Object value) {
      addHolder(value)..append(value);
      return this;
    }

    
Adds an unnamed value to the formatted output.

It is strongly encouraged to use add(java.lang.String,boolean) instead and give value a readable name.

Since:
11.0 (source-compatible since 2.0)
    public ToStringHelper addValue(boolean value) {
      addHolder()..append(value);
      return this;
    }

    
Adds an unnamed value to the formatted output.

It is strongly encouraged to use add(java.lang.String,char) instead and give value a readable name.

Since:
11.0 (source-compatible since 2.0)
    public ToStringHelper addValue(char value) {
      addHolder()..append(value);
      return this;
    }

    
Adds an unnamed value to the formatted output.

It is strongly encouraged to use add(java.lang.String,double) instead and give value a readable name.

Since:
11.0 (source-compatible since 2.0)
    public ToStringHelper addValue(double value) {
      addHolder()..append(value);
      return this;
    }

    
Adds an unnamed value to the formatted output.

It is strongly encouraged to use add(java.lang.String,float) instead and give value a readable name.

Since:
11.0 (source-compatible since 2.0)
    public ToStringHelper addValue(float value) {
      addHolder()..append(value);
      return this;
    }

    
Adds an unnamed value to the formatted output.

It is strongly encouraged to use add(java.lang.String,int) instead and give value a readable name.

Since:
11.0 (source-compatible since 2.0)
    public ToStringHelper addValue(int value) {
      addHolder()..append(value);
      return this;
    }

    
Adds an unnamed value to the formatted output.

It is strongly encouraged to use add(java.lang.String,long) instead and give value a readable name.

Since:
11.0 (source-compatible since 2.0)
    public ToStringHelper addValue(long value) {
      addHolder()..append(value);
      return this;
    }

    
Returns a string in the format specified by Objects.toStringHelper(java.lang.Object).
    @Override public String toString() {
      // create a copy to keep it consistent in case value changes
      boolean omitNullValuesSnapshot = ;
      boolean needsSeparator = false;
      StringBuilder builder = new StringBuilder(32).append()
          .append('{');
      for (ValueHolder valueHolder : ) {
        if (!omitNullValuesSnapshot || !valueHolder.isNull) {
          if (needsSeparator) {
            builder.append(", ");
          } else {
            needsSeparator = true;
          }
          // must explicitly cast it, otherwise GWT tests might fail because
          // it tries to access StringBuilder.append(StringBuilder), which is
          // a private method
          // TODO(user): change once 5904010 is fixed
          CharSequence sequence = valueHolder.builder;
          builder.append(sequence);
        }
      }
      return builder.append('}').toString();
    }
    private ValueHolder addHolder() {
      ValueHolder valueHolder = new ValueHolder();
      .add(valueHolder);
      return valueHolder;
    }
    private ValueHolder addHolder(@Nullable Object value) {
      ValueHolder valueHolder = addHolder();
      valueHolder.isNull = (value == null);
      return valueHolder;
    }
    private static final class ValueHolder {
      final StringBuilder builder = new StringBuilder();
      boolean isNull;
    }
  }
New to GrepCode? Check out our FAQ X