Thread: Couple Useful Utility Classes

Page 1 of 2 12 LastLast
Results 1 to 10 of 12
  1. #1 Couple Useful Utility Classes 
    Java Developer

    Celty's Avatar
    Join Date
    Aug 2013
    Age
    27
    Posts
    355
    Thanks given
    94
    Thanks received
    91
    Rep Power
    173
    Made a couple of utility classes for a project I'm working on I'm sure someone with find good use for these for RSPS or just help them save time.

    AttributeManager.java

    [Description]
    This class acts as a manager that is declared for a Type to stores object for that Type for temporary use.


    Code:
    package com.anezka.util;
    
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * 
     * @author Anežka Lane
     * 
     * This is a utility class that minipulates a {@code HashMap} to purpose 
     * temporary {@code Object}(s) for an existing {@code Objects}.
     */
    public class AttributeManager {
    	
    	/**
    	 * A {@code HashMap} that contains the temporay attributes.
    	 */
    	private final Map<String, Object> attributes = new HashMap<String, Object>();
    
    	/**
    	 * Creates a new attribute if the {@code HashMap}'s {@value key} doesn't already exist.
    	 * @param key The key to access the attribute.
    	 * @param value The value of the object.
    	 */
    	public void create(String key, Object value) {
    		this.attributes.putIfAbsent(key, value);
    	}
    	
    	/**
    	 * Minipulates the value of an existing {@code HashMap}'s {@value key}.
    	 * @param key The key to access the attribute.
    	 * @param value The new value of the object.
    	 */
    	public void setValueOf(String key, Object value) {
    		if(!attributes.containsKey(key)) {
    			System.out.println("[Attribute Manager] detected null key query. inquery denied.");
    			return;
    		}
    		attributes.put(key, value);
    	}
    	
    	/**
    	 * Removes a existing attribute from the {@code HashMap}.
    	 * @param key The key for the entry to be removed.
    	 */
    	public void remove(String key) {
    		if(!attributes.containsKey(key)) {
    			System.out.println("[Attribute Manager] detected null key query. inquery denied.");
    			return;
    		}
    		this.attributes.remove(key);
    	}
    	
    	/**
    	 * A query for an attribute.
    	 * @param key The key for the attribute being queried.
    	 * @return The Attribute.
    	 */
    	public Object get(String key) {
    		if(!attributes.containsKey(key)) {
    			System.out.println("[Attribute Manager] detected null key query. inquery denied.");
    			return null;
    		}
    		return attributes.get(key);
    	}
    
    }
    RandomUtil.java

    [Description]
    Contains some useful functional methods using the random generator.

    Code:
    package com.anezka.util;
    
    import java.util.List;
    import java.util.Map;
    import java.util.Random;
    
    /**
     * 
     * @author Anežka Lane
     *
     * A utility class which contains functionality and output 
     * using the random utility.
     */
    public class RandomUtil {
    	
    	private static Random random = new Random();
    	
    	public static int randomInt() {
    		return random.nextInt();
    	}
    	
    	public static int randomMaximumInt(int max) {
    		return random.nextInt(max);
    	}
    	
    	public static int randomMinimumInt(int min) {
    		return (random.nextInt() + min);
    	}
    	
    	public static int randomWithinRangeInt(int min, int max) {
    		return (random.nextInt(max) + min);
    	}
    	
    	public static double randomDouble() {
    		return random.nextDouble();
    	}
    	
    	public static double randomMaximumDouble(double max) {
    		double value = random.nextDouble();
    		return (value > max ? max : value);
    	}
    	
    	public static double randomMinimumDouble(double min) {
    		return (random.nextDouble() + min);
    	}
    	
    	public static double randomWithinRangeDouble(double min, double max) {
    		return (randomMaximumDouble(max) + min);
    	}
    	
    	public static boolean randomFlag() {
    		return random.nextBoolean();
    	}
        
        public static <T> T randomElement(T[] array) {
            return array[random.nextInt(array.length)];
        }
    
        public static <T> T randomElement(List<T> list) {
        	if(list.isEmpty()) {
        		return null;
        	}
            return list.get(random.nextInt(list.size()));
        }
        
        public static Object randomEntryKey(Map<?, ?> map) {
        	if(map.isEmpty()) {
        		return null;
        	}
        	Object[] keys = map.keySet().toArray();
        	return keys[random.nextInt(keys.length)];
        }
        
        public static Object randomEntryValue(Map<?, ?> map) {
        	if(map.isEmpty()) {
        		return null;
        	}
        	Object[] values = map.values().toArray();
        	return values[random.nextInt(values.length)];
        }
    
    }
    Reply With Quote  
     

  2. Thankful user:


  3. #2  
    Renown Programmer & Respected Member

    Ryley's Avatar
    Join Date
    Aug 2011
    Posts
    597
    Thanks given
    253
    Thanks received
    520
    Discord
    View profile
    Rep Power
    1332
    Your attribute map is not a good idea at all, that could easily cause unknown null pointer and class cast exceptions if used improperly. This is one of those things where type safety is _extremely_ important!

    Edit generics are your friend; you can turn some of the naughty code such as this:
    Code:
        public static <T> T randomElement(List<T> list) {
        	if(list.isEmpty()) {
        		return null;
        	}
            return list.get(random.nextInt(list.size()));
        }
    into this:

    Code:
    	public static <E, T extends Collection<E>> E randomElement(T collection) {
    		E element = Iterables.get(collection, random.nextInt(collection.size()));
                    return element;
    	}
    With that you can retrieve a random element of any collection type, not only lists.

    Also, please stop using null for state! Use optionals instead to prevent unexpected behavior if null is not planned for in your implementation!

    Code:
    	public static <E, T extends Collection<E>> E randomElement(T collection) {
    		E empty = (E) Optional.empty();
    		if (collection.size() == 0) {
    			return empty;
    		}
    
    		E element = Iterables.get(collection, random.nextInt(collection.size()));
    		Optional<E> optional = Optional.ofNullable(element);
    
    		return optional.isPresent() ? optional.get() : empty;
    	}
    Reply With Quote  
     

  4. Thankful users:


  5. #3  
    (Official) Thanksgiver

    Arham's Avatar
    Join Date
    Jan 2013
    Age
    20
    Posts
    3,377
    Thanks given
    7,120
    Thanks received
    1,879
    Discord
    View profile
    Rep Power
    3454
    ^ Java 8 powerrrrrrrrrr
    Quote Originally Posted by MrClassic View Post
    Arham is the official thanker!
    List of my work [Only registered and activated users can see links. ]!
    Reply With Quote  
     

  6. #4  
    Registered Member
    BenBeri's Avatar
    Join Date
    Jan 2013
    Posts
    484
    Thanks given
    57
    Thanks received
    130
    Discord
    View profile
    Rep Power
    248
    Quote Originally Posted by arham 4 View Post
    ^ Java 8 powerrrrrrrrrr
    Wut? that shit exists in Java 7 and probably 6, didn't check.
    Reply With Quote  
     

  7. #5  
    (Official) Thanksgiver

    Arham's Avatar
    Join Date
    Jan 2013
    Age
    20
    Posts
    3,377
    Thanks given
    7,120
    Thanks received
    1,879
    Discord
    View profile
    Rep Power
    3454
    Quote Originally Posted by JonyFX View Post
    Wut? that shit exists in Java 7 and probably 6, didn't check.
    Thought Optional.empty() was added in Java 8?
    Quote Originally Posted by MrClassic View Post
    Arham is the official thanker!
    List of my work [Only registered and activated users can see links. ]!
    Reply With Quote  
     

  8. #6  
    Java Developer

    Celty's Avatar
    Join Date
    Aug 2013
    Age
    27
    Posts
    355
    Thanks given
    94
    Thanks received
    91
    Rep Power
    173
    Quote Originally Posted by Ryley View Post
    Your attribute map is not a good idea at all, that could easily cause unknown null pointer and class cast exceptions if used improperly. This is one of those things where type safety is _extremely_ important!

    Edit generics are your friend; you can turn some of the naughty code such as this:
    Code:
        public static <T> T randomElement(List<T> list) {
        	if(list.isEmpty()) {
        		return null;
        	}
            return list.get(random.nextInt(list.size()));
        }
    into this:

    Code:
    	public static <E, T extends Collection<E>> E randomElement(T collection) {
    		E element = Iterables.get(collection, random.nextInt(collection.size()));
                    return element;
    	}
    With that you can retrieve a random element of any collection type, not only lists.

    Also, please stop using null for state! Use optionals instead to prevent unexpected behavior if null is not planned for in your implementation!

    Code:
    	public static <E, T extends Collection<E>> E randomElement(T collection) {
    		E empty = (E) Optional.empty();
    		if (collection.size() == 0) {
    			return empty;
    		}
    
    		E element = Iterables.get(collection, random.nextInt(collection.size()));
    		Optional<E> optional = Optional.ofNullable(element);
    
    		return optional.isPresent() ? optional.get() : empty;
    	}
    Okay thanks for the info.

    Quote Originally Posted by arham 4 View Post
    Thought Optional.empty() was added in Java 8?
    Optional was added in 1.8
    Reply With Quote  
     

  9. #7  
    Donator

    Jason's Avatar
    Join Date
    Aug 2009
    Posts
    6,108
    Thanks given
    2,402
    Thanks received
    2,825
    Rep Power
    4604
    The AttributeManager is a great idea, good job. I've done something very similar except I allowed for the class containing the attribute methods to be abstract and allowed for them to be serialized as well so they could be deserialized upon game startup to restore previous values, it's very useful.
    Reply With Quote  
     

  10. Thankful user:


  11. #8  
    Renown Programmer & Respected Member

    Ryley's Avatar
    Join Date
    Aug 2011
    Posts
    597
    Thanks given
    253
    Thanks received
    520
    Discord
    View profile
    Rep Power
    1332
    Quote Originally Posted by arham 4 View Post
    Thought Optional.empty() was added in Java 8?
    Iterables, Optional and other Java 8 features have existed in Google Guava since Java 5.
    Reply With Quote  
     

  12. Thankful user:


  13. #9  
    q.q


    Join Date
    Dec 2010
    Posts
    6,535
    Thanks given
    1,072
    Thanks received
    3,534
    Rep Power
    4752
    You should include in the documentation weather a random is inclusive or exlusive of the number you supply for max/range functions

    otherwise you'll run into headaches when you start actually using them
    Reply With Quote  
     

  14. Thankful user:


  15. #10  
    Ignorance is always an excuse

    Mikee's Avatar
    Join Date
    Nov 2009
    Posts
    2,373
    Thanks given
    732
    Thanks received
    490
    Rep Power
    656
    Cool stuff bro

    [Only registered and activated users can see links. ]

    The day Aj repped me, my life changed forever
    Quote Originally Posted by Aj View Post
    Rep++ for you
    Reply With Quote  
     

Page 1 of 2 12 LastLast

Thread Information
Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)


User Tag List

Similar Threads

  1. Combat style management utility class
    By Maxi in forum Snippets
    Replies: 12
    Last Post: 08-02-2011, 03:07 PM
  2. Useful Utilities for Dates
    By JavaStrong in forum Snippets
    Replies: 3
    Last Post: 04-07-2011, 09:12 PM
  3. Using Timer class, API
    By Greyfield in forum Snippets
    Replies: 28
    Last Post: 03-18-2010, 06:29 PM
  4. RuntimeMXBean - useful utility things
    By gnarly in forum Application Development
    Replies: 15
    Last Post: 06-02-2009, 04:23 PM
  5. Stop using Multi-Classes for same packet types!
    By Impulser in forum Tutorials
    Replies: 5
    Last Post: 06-22-2008, 10:24 PM
Posting Permissions
  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •