smallseo.info

guava

Google Core Libraries for Java 6+

Managing highly repetitive code and documentation in Java

Highly repetitive code is generally a bad thing, and there are design patterns that can help minimize this. However, sometimes it's simply inevitable due to the constraints of the language itself. Take the following example from java.util.Arrays:

/**
 * Assigns the specified long value to each element of the specified
 * range of the specified array of longs.  The range to be filled
 * extends from index <tt>fromIndex</tt>, inclusive, to index
 * <tt>toIndex</tt>, exclusive.  (If <tt>fromIndex==toIndex</tt>, the
 * range to be filled is empty.)
 *
 * @param a the array to be filled
 * @param fromIndex the index of the first element (inclusive) to be
 *        filled with the specified value
 * @param toIndex the index of the last element (exclusive) to be
 *        filled with the specified value
 * @param val the value to be stored in all elements of the array
 * @throws IllegalArgumentException if <tt>fromIndex &gt; toIndex</tt>
 * @throws ArrayIndexOutOfBoundsException if <tt>fromIndex &lt; 0</tt> or
 *         <tt>toIndex &gt; a.length</tt>
 */
public static void fill(long[] a, int fromIndex, int toIndex, long val) {
    rangeCheck(a.length, fromIndex, toIndex);
    for (int i=fromIndex; i<toIndex; i++)
        a[i] = val;
}

The above snippet appears in the source code 8 times, with very little variation in the documentation/method signature but exactly the same method body, one for each of the root array types int[], short[], char[], byte[], boolean[], double[], float[], and Object[].

I believe that unless one resorts to reflection (which is an entirely different subject in itself), this repetition is inevitable. I understand that as a utility class, such high concentration of repetitive Java code is highly atypical, but even with the best practice, repetition does happen! Refactoring doesn't always work because it's not always possible (the obvious case is when the repetition is in the documentation).

Obviously maintaining this source code is a nightmare. A slight typo in the documentation, or a minor bug in the implementation, is multiplied by however many repetitions was made. In fact, the best example happens to involve this exact class:

Google Research Blog - Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken (by Joshua Bloch, Software Engineer)

The bug is a surprisingly subtle one, occurring in what many thought to be just a simple and straightforward algorithm.

    // int mid =(low + high) / 2; // the bug
    int mid = (low + high) >>> 1; // the fix

The above line appears 11 times in the source code!

So my questions are:

  • How are these kinds of repetitive Java code/documentation handled in practice? How are they developed, maintained, and tested?
    • Do you start with "the original", and make it as mature as possible, and then copy and paste as necessary and hope you didn't make a mistake?
    • And if you did make a mistake in the original, then just fix it everywhere, unless you're comfortable with deleting the copies and repeating the whole replication process?
    • And you apply this same process for the testing code as well?
  • Would Java benefit from some sort of limited-use source code preprocessing for this kind of thing?
    • Perhaps Sun has their own preprocessor to help write, maintain, document and test these kind of repetitive library code?

A comment requested another example, so I pulled this one from Google Collections: com.google.common.base.Predicates lines 276-310 (AndPredicate) vs lines 312-346 (OrPredicate).

The source for these two classes are identical, except for:

  • AndPredicate vs OrPredicate (each appears 5 times in its class)
  • "And(" vs Or(" (in the respective toString() methods)
  • #and vs #or (in the @see Javadoc comments)
  • true vs false (in apply; ! can be rewritten out of the expression)
  • -1 /* all bits on */ vs 0 /* all bits off */ in hashCode()
  • &= vs |= in hashCode()

Source: (StackOverflow)

Guava: Why is there no Lists.filter() function?

is there a reason there's

Lists.transform()

but no

Lists.filter()?

How do i filter a list correctly? I could use

new List(Collection2.filter())

of course, but this way it's not guaranteed that my ordering stays the same, if i understand correctly.


Source: (StackOverflow)

What's the point of Guava's Optional class

I've recently read about this and seen people using this class, but in pretty much all cases, using null would've worked as well - if not more intuitively. Can someone provide a concrete example where Optional would achieve something that null couldn't or in a much cleaner way? The only thing I can think of is to use it with Maps that don't accept null keys, but even that could be done with a side "mapping" of null's value. Can anyone provide me with a more convincing argument? Thank you.


Source: (StackOverflow)

Predicate in Java

I am going through the code which uses Predicate in Java. I have never used predicate. Can someone guide me to any tutorial or conceptual explanation of predicate and their implementation in java ? Google didnt help much...


Source: (StackOverflow)

How is Guava Splitter.onPattern(..).split() different from String.split(..)?

I recently harnessed the power of a look-ahead regular expression to split a String:

"abc8".split("(?=\\d)|\\W")

If printed to the console this expression returns:

[abc, 8]

Very pleased with this result, I wanted to transfer this to Guava for further development, which looked like this:

Splitter.onPattern("(?=\\d)|\\W").split("abc8")

To my surprise the output changed to:

[abc]

Why?


Source: (StackOverflow)

The Guava library for java; what are its most useful and/or hidden features [closed]

I have had a quick scan of the guava api and the new collection types it provides(multimap and bimap for example appear useful) and I am thinking of including the library in the project(s) I work on. However, I also have a reticence to include libraries willy-nilly if they are of no great benefit and learning the features wastes valuable time.

Have you included the Guava library in your project and has it proved useful in any unexpected way ? Would you always use it in the future ? What has been its main benefit/time saver? What are its hidden features ?


Source: (StackOverflow)

Should I use Java8/Guava Optional for every method that may return null?

Optional is used to represent nullable object, Some uses of this class include

  1. As a method return type, as an alternative to returning null to
    indicate that no value was available
  2. To distinguish between "unknown" (for example, not present in a map) and "known to have no value" (present in the map, with value
    Optional.absent())
  3. To wrap nullable references for storage in a collection that does not support null (though there are several other approaches to this that should be considered first)

For the first case, do I need to return Optional in all nullable return method?


Source: (StackOverflow)

Google Guava isNullOrEmpty for collections

I see that Guava has isNullOrEmpty utility method for Strings

Strings.isNullOrEmpty(str)

Do we have anything similar for Lists? Something like

Lists.isNullOrEmpty(list)

which should be equivalent to

list == null || list.isEmpty()

Also, do we have anything similar for Arrays? Something like

Arrays.isNullOrEmpty(arr)

which should be equivalent to

arr == null || arr.length == 0

Source: (StackOverflow)

Google-guava checkNotNull and IntelliJ IDEA's "may produce java.lang.NullPointerException"

Is there any way to suppress this warning:

    MyClass object = null;

    /*Some code that 'might' set this object but I know it will*/      


    Preconditions.checkNotNull(object); 
    //when "assert object != null" is used here no warning is shown

    merged.setName(dRElement.getName());
    //"May produce 'java.lang.NullPointerException'" warning here 

I'm using IntelliJ IDEA 10.5 and I know this warning is unnecessary however I would like to suppress it just here and avoid switching inspections off.


Source: (StackOverflow)

Guava libraries and GWT

Just discovered the Guava libraries project.

Do these work with GWT?


Source: (StackOverflow)

is guava-libraries available in maven repo?

I am looking to find guava-libraries in maven repository. It looks like guava is adding more features to google-collections library.


Source: (StackOverflow)

What are the big improvements between guava and apache equivalent libraries?

We currently use apache collections, string utils, etc. I need to decide if we should switch from the apache foundations implementation.

The important criteria is ease of developers use. Performance/memory usage is not yet an important issue for us. Speed of development is the key criteria at this point.

I would appreciate opinions about how the developer's life became significantly easier with guava.


Source: (StackOverflow)

Getting default value for java primitive types

I have a java primitive type at hand:

Class c = int.class; // or long.class, or boolean.class

I'd like to get a 'default value' for this class - specifically the value is assigned to fields of this type if they are not initialized. E.g., '0' for a number, 'false' for a boolean.

Is there a generic way to do this? I tried

c.newInstance()

But I'm getting an InstantiationException, and not a default instance.


Source: (StackOverflow)

Guava: how to combine filter and transform?

I have a collection of Strings, and I would like to convert it to a collection of strings were all empty or null Strings are removed and all others are trimmed.

I can do it in two steps:

final List<String> tokens =
    Lists.newArrayList(" some ", null, "stuff\t", "", " \nhere");
final Collection<String> filtered =
    Collections2.filter(
        Collections2.transform(tokens, new Function<String, String>(){

            // This is a substitute for StringUtils.stripToEmpty()
            // why doesn't Guava have stuff like that?
            @Override
            public String apply(final String input){
                return input == null ? "" : input.trim();
            }
        }), new Predicate<String>(){

            @Override
            public boolean apply(final String input){
                return !Strings.isNullOrEmpty(input);
            }

        });
System.out.println(filtered);
// Output, as desired: [some, stuff, here]

But is there a Guava way of combining the two actions into one step?


Source: (StackOverflow)

initializing a Guava ImmutableMap

Guava offers a nice shortcut way of initializing a map. However I get the following compiler error (Eclipse Indigo) when my map initializer gets to nine entries.

The method of(K, V, K, V, K, V, K, V, K, V) in the type ImmutableMap is not applicable for the arguments (String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String, String)

ImmutableMap<String,String> myMap = ImmutableMap.of(
        "key1", "value1", 
        "key2", "value2", 
        "key3", "value3", 
        "key4", "value4", 
        "key5", "value5", 
        "key6", "value6", 
        "key7", "value7", 
        "key8", "value8", 
        "key9", "value9"
        );

The message appears to say that an ImmutableMap has a maximum size of four pairs of key,value. Obviously, this cannot be the case but I can't figure out what to do to increase the size of my initializer.

Can someone tell me what is missing?


Source: (StackOverflow)