Peer-reviewed code snippets that anyone can edit
follow refactory on twitter
blog
feedback
A wiki for useful code snippets
Bugs? Suggestions?
38-107-191-81
create/login
options
RECENT
STUBS/REQUESTS
STARRED
ACTIVITY
ADD
Add a snippet
Your work won't be attributed to you
because you aren't logged in.
Login using OpenID or an existing username, or create a username
(no email required) before posting.
Snippet title
short summary
Was this snippet already added?
Languages
Comma separated. Like
ruby, rails
or
java, swing
Keywords
Comma separated. Like
file, network
Mark as stub
Snippet
Wrap code in
[code=
language
][/code]
- Use
WikiText markup
outside of [code] tags
This is a Java trick which involves creating an anonymous class with an initialiser block, eg. [code=java] new Object() {{ // Initialisation stuff here }}; [/code] It's especially useful for collections: [code=java] List<Integer> list = new ArrayList<Integer>() {{ add(1); add(2); add(3); add(4); add(5); }}; System.out.println(list); [/code] [code=java] Map<Integer, String> map = new HashMap<Integer, String>() {{ put(1, "one"); put(2, "two"); put(3, "three"); put(4, "four"); put(5, "five"); }}; System.out.println(map); [/code] But can also be useful in GUI programming: [code=java] JFrame frame = new JFrame() {{ setDefaultCloseOperation(EXIT_ON_CLOSE); add(new JLabel("Hello, World!")); pack(); }}; frame.setVisible(true); [/code] Be careful when using this, however, because any object created using double brace initialisation belongs to an anonymous subclass, not the original class.
Log message
Human?
public snippets
This is a community-maintained collection of reusable code snippets.
Contribute something
without logging in, or improve existing contributions. All code is dedicated to the public domain unless otherwise specified.
stats
/
top contributers