Skip to content

Instantly share code, notes, and snippets.

@batmat
Created May 6, 2015 09:40
Show Gist options
  • Save batmat/30e1e742d15c6a973815 to your computer and use it in GitHub Desktop.
Save batmat/30e1e742d15c6a973815 to your computer and use it in GitHub Desktop.
SONARJAVA-985 Example
package xxxxx.utils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nonnull;
public class NonNullUtil
{
private NonNullUtil()
{
}
/**
* A partir d'une liste donnée, on retourne cette liste si elle n'est pas <code>null</code>, sinon on renvoie une
* ArrayList vide.
*
* @param list
* @return une liste non <code>null</code>
*/
@Nonnull
public static <T> List<T> getNonNullList(List<T> list)
{
if (list == null)
{
list = new ArrayList<>();
}
return list;
}
/**
* A partir d'un set donné, on retourne ce set si il n'est pas <code>null</code>, sinon on renvoit un HashSet vide.
*
* @param set
* @return un set non <code>null</code>
*/
@Nonnull
public static <T> Set<T> getNonNullSet(Set<T> set)
{
if (set == null)
{
set = new HashSet<>();
}
return set;
}
/**
* A partir d'une collection donnée, on retourne cette collection si elle n'est pas <code>null</code>, sinon on
* renvoie la deuxième collection passée en paramètre. Si jamais cette deuxième est null, alors on renvoie quand même
* une {@link ArrayList}.
*
* @param potentialNullCollection
* @param nonNullCollection
* @return une collection non <code>null</code>
*/
@SuppressWarnings("unchecked")
@Nonnull
public static <C extends Collection<T>, T> C getNonNullCollection(C potentialNullCollection, C nonNullCollection)
{
if (potentialNullCollection == null)
{
if (nonNullCollection == null)
{
nonNullCollection = (C)new ArrayList<T>();
}
return nonNullCollection;
}
return potentialNullCollection;
}
/**
* A partir d'une map donnée, on retourne cette map si elle n'est pas <code>null</code>, sinon on renvoie une HashMap
* vide.
*
* @param map
* @return une map non <code>null</code>
*/
@Nonnull
public static <K, V> Map<K, V> getNonNullMap(Map<K, V> map)
{
if (map == null)
{
map = new HashMap<>();
}
return map;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment