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 247303
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T21:14:53+00:00 2026-05-11T21:14:53+00:00

This is more a gotcha I wanted to share than a question: when printing

  • 0

This is more a gotcha I wanted to share than a question: when printing with toString(), Java will detect direct cycles in a Collection (where the Collection refers to itself), but not indirect cycles (where a Collection refers to another Collection which refers to the first one – or with more steps).

import java.util.*;
public class ShonkyCycle {
  static public void main(String[] args) {
    List a = new LinkedList();
    a.add(a);                      // direct cycle
    System.out.println(a);         // works:  [(this Collection)]

    List b = new LinkedList();
    a.add(b);
    b.add(a);                      // indirect cycle
    System.out.println(a);         // shonky:  causes infinite loop!
  }
}

This was a real gotcha for me, because it occurred in debugging code to print out the Collection (I was surprised when it caught a direct cycle, so I assumed incorrectly that they had implemented the check in general). There is a question: why?

The explanation I can think of is that it is very inexpensive to check for a collection that refers to itself, as you only need to store the collection (which you have already), but for longer cycles, you need to store all the collections you encounter, starting from the root. Additionally, you might not be able to tell for sure what the root is, and so you’d have to store every collection in the system – which you do anyway – but you’d also have to do a hash lookup on every collection element. It’s very expensive for the relatively rare case of cycles (in most programming). (I think) the only reason it checks for direct cycles is because it so cheap (one reference comparison).

OK… I’ve kinda answered my own question – but have I missed anything important? Anyone want to add anything?


Clarification: I now realize the problem I saw is specific to printing a Collection (i.e. the toString() method). There’s no problem with cycles per se (I use them myself and need to have them); the problem is that Java can’t print them. Edit Andrzej Doyle points out it’s not just collections, but any object whose toString is called.

Given that it’s constrained to this method, here’s an algorithm to check for it:

  • the root is the object that the first toString() is invoked on (to determine this, you need to maintain state on whether a toString is currently in progress or not; so this is inconvenient).
    • as you traverse each object, you add it to an IdentityHashMap, along with a unique identifier (e.g. an incremented index).
    • but if this object is already in the Map, write out its identifier instead.

This approach also correctly renders multirefs (a node that is referred to more than once).

The memory cost is the IdentityHashMap (one reference and index per object); the complexity cost is a hash lookup for every node in the directed graph (i.e. each object that is printed).

  • 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-05-11T21:14:53+00:00Added an answer on May 11, 2026 at 9:14 pm

    I think fundamentally it’s because while the language tries to stop you from shooting yourself in the foot, it shouldn’t really do so in a way that’s expensive. So while it’s almost free to compare object pointers (e.g. does obj == this) anything beyond that involves invoking methods on the object you’re passing in.

    And at this point the library code doesn’t know anything about the objects you’re passing in. For one, the generics implementation doesn’t know if they’re instances of Collection (or Iterable) themselves, and while it could find this out via instanceof, who’s to say whether it’s a “collection-like” object that isn’t actually a collection, but still contains a deferred circular reference? Secondly, even if it is a collection there’s no telling what it’s actual implementation and thus behaviour is like. Theoretically one could have a collection containing all the Longs which is going to be used lazily; but since the library doesn’t know this it would be hideously expensive to iterate over every entry. Or in fact one could even design a collection with an Iterator that never terminated (though this would be difficult to use in practice because so many constructs/library classes assume that hasNext will eventually return false).

    So it basically comes down to an unknown, possibly infinite cost in order to stop you from doing something that might not actually be an issue anyway.

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

Sidebar

Ask A Question

Stats

  • Questions 123k
  • Answers 123k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Check out the Matlab Engine. There's even an interesting article… May 12, 2026 at 1:10 am
  • Editorial Team
    Editorial Team added an answer Here http://blogs.securancy.com/post/ASPNET-MVC-Subdomain-Routing.aspx May 12, 2026 at 1:10 am
  • Editorial Team
    Editorial Team added an answer That is exactly what most GUI designers (e.g. NetBeans' Matisse)… May 12, 2026 at 1:10 am

Related Questions

I'm seeking graphic advice on how to have your interface look better. So far
Okay, here's the scenario. I have a utility that processes tons of records, and
I have a new app I'll be working on where I have to generate
I am using LINQ to query a generic dictionary and then use the result

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.