Java中的char、Character和CharSequence的区别

news2024/7/4 6:15:00

char 与 Character

char是一种基本的数据类型,Character是char类型的包装类,即通过Character创建出来的是一种对象。 

Character是char的包装类,就像Integer和int,以及Long和long一样。

包装类和基本类型可以自动转换,这是jdk1.5(5.0)的新特性,叫做自动封箱和自动解封

自动拆箱、自动装箱

char ch='a';

Character ch1=ch;//自动封箱

Character c=new Character(a);

char c1=c;//自动解封

如何理解Java中的自动拆箱和自动装箱? 

定义:基本数据类型包装类之间可以自动地相互转换

理解:装箱就是自动将基本数据类型转换为封装类型,拆箱就是自动将封装类型转换为基本数据类型。

// 自动装箱
1. Integer a = 100;
// 自动拆箱
2. int b = a;

自动装箱,相当于Java编译器替我们执行了 Integer.valueOf(XXX);

自动拆箱,相当于Java编译器替我们执行了 Integer.intValue(XXX);

CharSequence

CharSequence是一个描述字符串结构的接口,在这个接口里面一般发现有三种常用的子类:

  • 获取指定索引的字符:public char charAt​(int index) 
  • 获取字符串长度:public int length​()
  • 截取部分字符串:public CharSequence subSequence​(int start, int end)

截取部分字符串代码样例

public static void main(String[] args) {
    CharSequence str = "hello world";
    CharSequence sub = str.subSequence(6,11);
    System.out.println(sub);
}

CharSequence接口源码

package java.lang;

import java.util.NoSuchElementException;
import java.util.PrimitiveIterator;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.IntConsumer;
import java.util.stream.IntStream;
import java.util.stream.StreamSupport;

/**
 * A <tt>CharSequence</tt> is a readable sequence of <code>char</code> values. This
 * interface provides uniform, read-only access to many different kinds of
 * <code>char</code> sequences.
 * A <code>char</code> value represents a character in the <i>Basic
 * Multilingual Plane (BMP)</i> or a surrogate. Refer to <a
 * href="Character.html#unicode">Unicode Character Representation</a> for details.
 *
 * <p> This interface does not refine the general contracts of the {@link
 * java.lang.Object#equals(java.lang.Object) equals} and {@link
 * java.lang.Object#hashCode() hashCode} methods.  The result of comparing two
 * objects that implement <tt>CharSequence</tt> is therefore, in general,
 * undefined.  Each object may be implemented by a different class, and there
 * is no guarantee that each class will be capable of testing its instances
 * for equality with those of the other.  It is therefore inappropriate to use
 * arbitrary <tt>CharSequence</tt> instances as elements in a set or as keys in
 * a map. </p>
 *
 * @author Mike McCloskey
 * @since 1.4
 * @spec JSR-51
 */

public interface CharSequence {

    /**
     * Returns the length of this character sequence.  The length is the number
     * of 16-bit <code>char</code>s in the sequence.
     *
     * @return  the number of <code>char</code>s in this sequence
     */
    int length();

    /**
     * Returns the <code>char</code> value at the specified index.  An index ranges from zero
     * to <tt>length() - 1</tt>.  The first <code>char</code> value of the sequence is at
     * index zero, the next at index one, and so on, as for array
     * indexing.
     *
     * <p>If the <code>char</code> value specified by the index is a
     * <a href="{@docRoot}/java/lang/Character.html#unicode">surrogate</a>, the surrogate
     * value is returned.
     *
     * @param   index   the index of the <code>char</code> value to be returned
     *
     * @return  the specified <code>char</code> value
     *
     * @throws  IndexOutOfBoundsException
     *          if the <tt>index</tt> argument is negative or not less than
     *          <tt>length()</tt>
     */
    char charAt(int index);

    /**
     * Returns a <code>CharSequence</code> that is a subsequence of this sequence.
     * The subsequence starts with the <code>char</code> value at the specified index and
     * ends with the <code>char</code> value at index <tt>end - 1</tt>.  The length
     * (in <code>char</code>s) of the
     * returned sequence is <tt>end - start</tt>, so if <tt>start == end</tt>
     * then an empty sequence is returned.
     *
     * @param   start   the start index, inclusive
     * @param   end     the end index, exclusive
     *
     * @return  the specified subsequence
     *
     * @throws  IndexOutOfBoundsException
     *          if <tt>start</tt> or <tt>end</tt> are negative,
     *          if <tt>end</tt> is greater than <tt>length()</tt>,
     *          or if <tt>start</tt> is greater than <tt>end</tt>
     */
    CharSequence subSequence(int start, int end);

    /**
     * Returns a string containing the characters in this sequence in the same
     * order as this sequence.  The length of the string will be the length of
     * this sequence.
     *
     * @return  a string consisting of exactly this sequence of characters
     */
    public String toString();

    /**
     * Returns a stream of {@code int} zero-extending the {@code char} values
     * from this sequence.  Any char which maps to a <a
     * href="{@docRoot}/java/lang/Character.html#unicode">surrogate code
     * point</a> is passed through uninterpreted.
     *
     * <p>If the sequence is mutated while the stream is being read, the
     * result is undefined.
     *
     * @return an IntStream of char values from this sequence
     * @since 1.8
     */
    public default IntStream chars() {
        class CharIterator implements PrimitiveIterator.OfInt {
            int cur = 0;

            public boolean hasNext() {
                return cur < length();
            }

            public int nextInt() {
                if (hasNext()) {
                    return charAt(cur++);
                } else {
                    throw new NoSuchElementException();
                }
            }

            @Override
            public void forEachRemaining(IntConsumer block) {
                for (; cur < length(); cur++) {
                    block.accept(charAt(cur));
                }
            }
        }

        return StreamSupport.intStream(() ->
                Spliterators.spliterator(
                        new CharIterator(),
                        length(),
                        Spliterator.ORDERED),
                Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED,
                false);
    }

    /**
     * Returns a stream of code point values from this sequence.  Any surrogate
     * pairs encountered in the sequence are combined as if by {@linkplain
     * Character#toCodePoint Character.toCodePoint} and the result is passed
     * to the stream. Any other code units, including ordinary BMP characters,
     * unpaired surrogates, and undefined code units, are zero-extended to
     * {@code int} values which are then passed to the stream.
     *
     * <p>If the sequence is mutated while the stream is being read, the result
     * is undefined.
     *
     * @return an IntStream of Unicode code points from this sequence
     * @since 1.8
     */
    public default IntStream codePoints() {
        class CodePointIterator implements PrimitiveIterator.OfInt {
            int cur = 0;

            @Override
            public void forEachRemaining(IntConsumer block) {
                final int length = length();
                int i = cur;
                try {
                    while (i < length) {
                        char c1 = charAt(i++);
                        if (!Character.isHighSurrogate(c1) || i >= length) {
                            block.accept(c1);
                        } else {
                            char c2 = charAt(i);
                            if (Character.isLowSurrogate(c2)) {
                                i++;
                                block.accept(Character.toCodePoint(c1, c2));
                            } else {
                                block.accept(c1);
                            }
                        }
                    }
                } finally {
                    cur = i;
                }
            }

            public boolean hasNext() {
                return cur < length();
            }

            public int nextInt() {
                final int length = length();

                if (cur >= length) {
                    throw new NoSuchElementException();
                }
                char c1 = charAt(cur++);
                if (Character.isHighSurrogate(c1) && cur < length) {
                    char c2 = charAt(cur);
                    if (Character.isLowSurrogate(c2)) {
                        cur++;
                        return Character.toCodePoint(c1, c2);
                    }
                }
                return c1;
            }
        }

        return StreamSupport.intStream(() ->
                Spliterators.spliteratorUnknownSize(
                        new CodePointIterator(),
                        Spliterator.ORDERED),
                Spliterator.ORDERED,
                false);
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/28652.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

安泰测试-同惠TH2827精密LCR数字电桥产品性能特点

同惠(Tonghui)TH2827A/TH2827B/TH2827C型 LCR数字电桥 产品简介&#xff1a; TH2827A/TH2827B/TH2827C是具有多种功能和更高测试频率的新型LCR数字电桥&#xff0c;体积小&#xff0c;紧凑便携&#xff0c;便于上架使用。本系列仪器基本精度为0.05%&#xff0c;测试频率最高1M…

GitLab仓库管理系统安装详细步骤

前言 本案例安装 gitlab、jenkins、并部署springboot应用程序&#xff0c;所以准备了3台服务器。 服务器1&#xff1a;安装gitlab服务器2&#xff1a;安装jdk、maven、git、jenkins 因为jenkins需要jdk、maven、git服务器3&#xff1a;安装jdk。 jenkins自动部署的springboot…

多目标优化生态调度结果的预测方法研究——基于新蝙蝠算法(Matlab代码实现)

&#x1f352;&#x1f352;&#x1f352;欢迎关注&#x1f308;&#x1f308;&#x1f308; &#x1f4dd;个人主页&#xff1a;我爱Matlab &#x1f44d;点赞➕评论➕收藏 养成习惯&#xff08;一键三连&#xff09;&#x1f33b;&#x1f33b;&#x1f33b; &#x1f34c;希…

【CNN】ZFNet——让卷积神经网络不再是一个黑盒模型。

前言 ZFNet在2013年 ILSVRC 图像分类竞赛获得冠军&#xff0c;错误率11.19% &#xff0c;比2012年的AlexNet降低了5%&#xff0c;ZFNet是由 Matthew D.Zeiler 和 Rob Fergus 在 AlexNet 基础上提出的大型卷积网络。ZFNet解释了为什么卷积神经网络可以在图像分类上表现的如此出…

[MySQL]事务ACID详解

专栏简介 :MySql数据库从入门到进阶. 题目来源:leetcode,牛客,剑指offer. 创作目标:记录学习MySql学习历程 希望在提升自己的同时,帮助他人,,与大家一起共同进步,互相成长. 学历代表过去,能力代表现在,学习能力代表未来! 目录 1. 事务的概念 2. 事务的特性 3.事务控制语法…

【经验篇】Java使用ZMQ断线重连问题

简介 ZeroMQ是一个高性能的异步消息传递库&#xff0c;旨在用于分布式或者并发应用程序。它提供了一个消息队列&#xff0c;但与面向消息的中间件不同&#xff0c;ZeroMQ 系统可以在没有专用消息代理的情况下运行。 ZeroMQ 支持各种传输&#xff08;TCP、进程内、进程间、多播…

初步认识端口服务查询--netstat

转载连接&#xff1a;netstat详解 目录1、语法与参数概括2、输出释义2.1 以netstat -atnlp为例&#xff0c;解释输出结果中各列的含义2.2、以netstat -rn为例&#xff0c;解释输出结果中各列的含义3、实用命令4、项目中通过netstat查询某端口是否被占用netstat命令是一个监控TC…

Spring5源码3-BeanDefinition

1. BeanDefinition BeanDefinition在spring中贯穿始终&#xff0c;spring要根据BeanDefinition对象来实例化bean&#xff0c;只有把解析的标签&#xff0c;扫描的注解类封装成BeanDefinition对象&#xff0c;spring才能实例化bean beanDefinition主要实现类: ChildBeanDefini…

ADB安装及使用详解

一、ADB简介 1、什么是adb ADB 全称为 Android Debug Bridge&#xff0c;起到调试桥的作用&#xff0c;是一个客户端-服务器端程序。其中客户端是用来操作的电脑&#xff0c;服务端是 Android 设备。 ADB 也是 Android SDK 中的一个工具&#xff0c;可以直接操作管理 Androi…

K8s高可用集群搭建

K8s高可用集群搭建1 方案简介2 集群搭建2.1 安装要求2.2 准备环境2.3 master节点部署keepalived2.4 master节点部署haproxy2.5 所有节点安装docker/kubeadm/kubelet2.6 部署k8smaster012.7 安装集群网络2.8 k8smaster02加入节点2.9 k8snode01加入集群3 测试集群1 方案简介 用到…

Session-based Recommendation with Graph Neural Networks论文阅读笔记

1. Abstract &#xff08;1&#xff09;基于会话的推荐问题旨在基于匿名会话来预测用户的行为。 The problem of session-based recommendation aims to predict user actions based on anonymous sessions. &#xff08;2&#xff09; 以前的方法存在的不足&#xff1a;不足以…

day3-day4【代码随想录】长度最小的子数组

文章目录前言一、长度最小的子数组1、暴力求解&#xff1a;2、滑动窗口求解&#xff1a;二、最小覆盖子串&#xff08;乐扣76&#xff09;难难难难难三、水果成篮&#xff08;乐扣904&#xff09;四、最长重复子数组&#xff08;乐扣718&#xff09;前言 实现滑动窗口&#xf…

Android抓包工具——Fiddler

前言 &#x1f525;在平时和其他大佬交流时&#xff0c;总会出现这么些话&#xff0c;“抓个包看看就知道哪出问题了”&#xff0c;“抓流量啊&#xff0c;payload都在里面”&#xff0c;“这数据流怎么这么奇怪”。 &#x1f449;这里出现的名词&#xff0c;其实都是差不多的…

矩阵分析:特征值分解

矩阵分析&#xff1a;特征值分解前置知识空间变换伸缩旋转对称矩阵对称矩阵对角化正交矩阵向量的基基变换不同基下的向量变换逆矩阵不同基下的空间变换内积的几何意义特征值、特征向量特征值分解代码前置知识 空间变换 伸缩 一个矩阵其实就是一个线性变换&#xff0c;因为一个…

SpringCloud微服务(六)——Gateway路由网关

Gateway路由网关 Spring Cloud Spring Cloud Gateway统一访问接口的路由管理方式 作用 整合各个微服务功能&#xff0c;形成一套系统微服务网关实现日志统一纪录实现用户的操作跟踪统一用户权限认证路由转发、跨域设置、负载均衡、服务限流反向代理 微服务网关的概述 不同…

H2DCFDA | ROS 荧光探针检测法

H2DCFDA 工作液的配制1、储存液的配制&#xff1a;用 DMSO 配制 10 mM 的 H2DCFDA (2,000)&#xff0c;如用 1.03 mL DMSO 溶解 5 mg H2DCFDA。注&#xff1a;H2DCFDA 储存液建议分装后-20℃ 避光冻存&#xff0c;一个月。-80 半年。2、工作液的配制&#xff1a;用预热好的无血…

绘制文字(QFont字体)

QPainter绘制文字的话使用的函数为 QPainter::drawText() QPainter::drawText()有多种重载方式。 根据坐标直接绘画文字&#xff1a; void Widget::paintEvent(QPaintEvent *event)//绘图事件 {QPainter painter(this);painter.translate(100,100);//移动坐标painter.drawText(…

E. Sending a Sequence Over the Network(DP)

Problem - 1741E - Codeforces 序列a在网络上的发送情况如下。 序列a被分割成若干段&#xff08;序列的每个元素正好属于一个段&#xff0c;每个段是序列的一组连续元素&#xff09;。 对于每个段&#xff0c;它的长度被写在它的旁边&#xff0c;要么在它的左边&#xff0c;要…

递归展示树状图/树状表格

递归展示树状图一、数据库表设计二、后端java递归代码三、前端展示树状表格四、效果展示一、数据库表设计 这里我们采用自关联的设计&#xff0c;通过id和pid的对应来确认数据的上下级关系 建表语句&#xff0c;我这里把一级菜单的pid设置成了0 /*Navicat Premium Data Transfe…

Spring中Bean的作用域和生命周期

目录 Bean的作用域 singleton prototype request session application websocket 单例作用域和全局作用域的区别 Bean的生命周期 Bean的作用域 Bean的作用域是指Bean在Spring整个框架中的某种行为模式&#xff0c;比如singleton单例作用域&#xff0c;就表示Bean在整…