2

I want to get last element of HashSet.

So there is a last() method in TreeSet so, I thought to convert set to TreeSet and apply last() method on it so that I will get last element.

I tried below code :

Set<EnrollmentStatusTrack> set= new HashSet<EnrollmentStatusTrack>();
set=en.getEnrollmentStatusTracks();
TreeSet<EnrollmentStatusTrack> hashSetToTreeSet  = new TreeSet<EnrollmentStatusTrack>(set);  //here is the exception
EnrollmentStatusTrack entt=hashSetToTreeSet.last();

Then i get below exception:

java.lang.ClassCastException: com.barcouncil.entity.EnrollmentStatusTrack cannot be cast to java.lang.Comparable
    at java.util.TreeMap.compare(TreeMap.java:1290)
    at java.util.TreeMap.put(TreeMap.java:538)
    at java.util.TreeSet.add(TreeSet.java:255)
    at java.util.AbstractCollection.addAll(AbstractCollection.java:344)
    at java.util.TreeSet.addAll(TreeSet.java:312)
    at java.util.TreeSet.<init>(TreeSet.java:160)
    at com.barcouncil.dao.EnrollmentDaoImpl.searchReport(EnrollmentDaoImpl.java:994)
    at com.barcouncil.service.EnrollmentServiceImpl.searchReport(EnrollmentServiceImpl.java:278)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:343)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:198)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
    at com.sun.proxy.$Proxy1909.searchReport(Unknown Source)
    at com.barcouncil.controller.EnrollmentController.searchReport(EnrollmentController.java:984)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:908)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:320)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:200)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1100)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:687)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

Can any one help me with this? Or is there any other procedure to do so?

M. Justin
  • 14,487
  • 7
  • 91
  • 130
bharath varma
  • 61
  • 1
  • 7
  • A `HashSet` *doesn't have* a defined "last" element. – chrylis -cautiouslyoptimistic- Dec 13 '19 at 08:11
  • 1
    If you want the „last“ element of a HashSet, just grab **any** element of it, it would be the same like @chrylis-onstrike- said. So, it sounds more like a XY-problem. What‘s the real problem of your intention? – bobbel Dec 13 '19 at 08:28
  • Looking at the [self-answer](https://stackoverflow.com/a/59320014/1108305), it looks like the real request is to get the greatest element in the collection, according to a particular comparison function. Voting to close this as a duplicate of an existing question that does that. – M. Justin Aug 12 '23 at 04:50
  • Though it looks like I should have voted to close as a duplicate of this one instead, but if I retract my close vote I can't re-vote to close. https://stackoverflow.com/q/1669282/1108305 – M. Justin Aug 12 '23 at 04:51

4 Answers4

1

com.barcouncil.entity.EnrollmentStatusTrack cannot be cast to java.lang.Comparable

This means your EnrollmentStatusTrack class doesn't implement the Comparable interface, so you can't construct a TreeSet<EnrollmentStatusTrack> using a constructor that doesn't have a Comparator<EnrollmentStatusTrack> argument (since the TreeSet would have no way of comparing the elements added to it).

You can write:

Comprator<EnrollmentStatusTrack> comparator = ...
TreeSet<EnrollmentStatusTrack> hashSetToTreeSet  = new TreeSet<>(comparator);
hashSetToTreeSet.addAll(set);

where comparator implements the comparison logic.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • thank you for reply @Eran can you please tell what is that ````comparator=.....```` what should i do there – bharath varma Dec 13 '19 at 08:11
  • @bharathvarma it should be an instance of a class that implement the `Comparator` interface (having a `int compare(EnrollmentStatusTrack o1,EnrollmentStatusTrack o2)` method). How should two `EnrollmentStatusTrack` instance be compared? – Eran Dec 13 '19 at 08:14
0

You can define a compareTo() method in your EnrollmentStatusTrack class by implementing the Comparable interface. In the compareTo() method, you need to define the meaning of first/last element i.e. the ordering of the elements when the TreeSet is populated.

class EnrollmentStatusTrack implements Comparable<EnrollmentStatusTrack> {

    int size;

    EnrollmentStatusTrack(int s) {
        size = s;
    }

    public int compareTo(EnrollmentStatusTrack o) {
        return size - o.size;
    }
}
Amar Wadhwani
  • 67
  • 1
  • 10
0

my aim is to find last element so i have done like this

if(en.getEnrollmentStatusTracks() != null)
            {
            Set<EnrollmentStatusTrack> set= new HashSet<EnrollmentStatusTrack>();
            set=en.getEnrollmentStatusTracks();
            List<EnrollmentStatusTrack> list  = new ArrayList<EnrollmentStatusTrack>(set); 
            Collections.sort(list, Comparator.comparingInt(EnrollmentStatusTrack::getEnrollmentStatusTrackId)); 
            if(list.size() > 0)
            {
             ent=list.get(list.size() - 1);
            }
}
bharath varma
  • 61
  • 1
  • 7
0

It could very well be, that with "last" you do not mean the last in an internal ordering of EnrollmentStatusTrack, but the last added (because of the terms enrollment, status, track).

In that case use LinkedHashSet which is ordered on addition, like LinkedHashMap.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138