Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8248121
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T23:05:20+00:00 2026-06-07T23:05:20+00:00

I find my self having to export references to keys in an underlying Java

  • 0

I find my self having to export references to keys in an underlying Java collections map. I don’t want to give out references to the actual key objects but copies of them to ensure that nobody fiddles with the values and messes up the map. So I need to create a copy of an arbitrary generic type.

I already wrote a utility class that does this through in memory serialisation, but then noticed that Collections.nCopies also gives me copies of things.

So just to give some idea of what I am doing, I need to for instance access the next (higher/lower) key value given some other key value.

public class MapWrapper<T, K extends Comparable<K>>
    implements OtherThing<T, K>
{
    public K next (K current) {
        return ... cloned next highest key as per NavigableMap.higherKey()
    }
}

So the question is if it is better to copy the objects with

T copy = Collections.nCopies(1,item).get(0)

or to serialise the object and then deserialise it

final ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();
final ObjectOutputStream outputStream = new ObjectOutputStream(outputBuffer);
outputStream.writeObject(item);
outputStream.close();

final ByteArrayInputStream inputBuffer = new ByteArrayInputStream(buffer);
final ObjectInputStream inputStream = new ObjectInputStream(inputBuffer);T copy = null;
T item = null;
try {
    copy = (T)inputStream.readObject();
} catch (ClassNotFoundException e) {
    Logger.getLogger(SerialisationService.class.getName()).log(Level.WARNING, null, e);
}

inputStream.close();
inputBuffer.close();
outputBuffer.close();

A quick test with copying a Long shows that the Collections.nCopies is faster (0 ms / 8 ms). Is there some caveat to that method that I’m not able to think about at this late hour though, or can you think of an even better way of getting a copy of the keys?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T23:05:22+00:00Added an answer on June 7, 2026 at 11:05 pm

    There is a significant difference – Collections.nCopies doesn’t copy the object! It just returns a List containing n entries, all of which are the provided object (check the source!). Any changes made to anything you pick out from that list will be reflected in the original object. So this code:

    Point original = new Point(0, 0);
    Point supposedCopy = Collections.nCopies(1, original).get(0);
    supposedCopy.x = 13;
    System.out.println("x = " + original.x); 
    

    will print 13, not 0. Oops.

    A serialization roundtrip isn’t a bad idea. An alternative is using Cloneable, which unfortunately is kind of broken. Cloneable doesn’t declare clone(), but it is declared as protected in Object, so you have to invoke it by means of reflection.

    Personally, I’d prefer to use immutable objects in your situation, if possible.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Maven does a lot of neat things, but I find my self having to
I am having memory issues with iPython, and I find that calling %clear out
I find my self having a repeater control which is being databound to an
Am getting a warning for 'incomplete implementation', but can't find out why, having compared
During development i find my self often having to restart my application which in
I find my self lost while trying to create an actually pretty easy SQL
I find my self hard to design action enums for events. f.ex making calculation
I find my self in a situation where I have to choose between either
I find my self overriding Equals() and GetHashCode() frequently to implement the semantic that
I find the following example mildly surprising: >>> class Foo: def blah(self): pass >>>

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.