【Java数据结构与算法】第二十一章 元组

news2024/9/30 3:31:02

【Java数据结构与算法】第二十一章 元组

文章目录

  • 【Java数据结构与算法】第二十一章 元组
    • 1.概念
    • 2.自定义元组
    • 3.第三方Jar包

1.概念

元组(Tuple)是一种数据结构,可以存放多个元素,每个元素的数据类型可以不同。用List与Tuple类比,List只能存储一种数据类型,而Tuple可以存储多种数据类型

元组也是关系型数据库中的基本概念,表中的每行,或者说表中的每条记录,就是一个元组,每行的每列都可以是不同的数据类型

元组将一组对象直接打包存储为单一对象,这个对象只允许读取,不允许存放新的对象

2.自定义元组

二元组

public class TwoTuple<A, B>{
	public final A first;
	public final B second;
	
	public TwoTuple(A a, B b){
		this.first = a;
		this.second = b;
	}
}

三元组

public class ThreeTuple<A, B, C> extends TwoTuple<A, B>{
	public final C third;

	public ThreeTuple(A a, B b, C c){
		super(a, b);
		this.third = c;
	}	
}

元组操作工具类、测试类

/*
 * 元组辅助类:用于多种类型值的返回,如在分页的时候,后台存储过程既返回了查询得到的当页
 * 的数据(List类型),又得到了数据表中数据总数(Integer类型)
 * 使用泛型方法实现,利用参数类型推断,编译器可以找出具体的类型
 * 
public class TupleUtil{
	public static <A, B> TwoTuple<A, B> tuple(A a, B b){
		return new TwoTuple<A, B>(a, b);
	}

	public static <A, B, C> ThreeTuple<A, B. C> tuple(A a, B b, C c){
		return new ThreeTuple<A, B, C>(a, b, c);
	}

	//测试
	public static void main(String[] args){
		List<GoodsBean> goodsBeans = new ArrayList<GoodBean>();
		for(int i = 1; i < 26; i++){
			GoodsBean goodsBean = new GoodsBean();
			goodsBean.setGoodsId(i);
			goodsBeans.add(goodsBean);
		}
		Integer totalProperty = 47;
		TwoTuple<List<GoodsBean>, Integer> twoTuple = TupleUtil.tuple(goodsBeans, totalProperty);
		List<GoodsBean> list = twoTuple.first;
		Integer count = twoTuple.second;
	}
}

3.第三方Jar包

Maven坐标

<dependency>
	<groupId>org.javatuples</groupId>
	<artifactId>javatuples</artifactId>
	<version>1.2</version>
</dependency>

Jar包中的类主要是Tuple基础类、一元组、二元组…十元组,以及键值对元组
在这里插入图片描述
IValue3

package org.javatuples.valueintf;

public interface IValue3<X> {

    public X getValue3();
    
}

Triplet

package org.javatuples;

import java.util.Collection;
import java.util.Iterator;

import org.javatuples.valueintf.IValue0;
import org.javatuples.valueintf.IValue1;
import org.javatuples.valueintf.IValue2;

/**
 * <p>
 * A tuple of three elements.
 * </p> 
 * 
 * @since 1.0
 * 
 * @author Daniel Fern&aacute;ndez
 *
 */
public final class Triplet<A,B,C> 
        extends Tuple
        implements IValue0<A>,
                   IValue1<B>,
                   IValue2<C> {

    private static final long serialVersionUID = -1877265551599483740L;

    private static final int SIZE = 3;

    private final A val0;
    private final B val1;
    private final C val2;

    public static <A,B,C> Triplet<A,B,C> with(final A value0, final B value1, final C value2) {
        return new Triplet<A,B,C>(value0,value1,value2);
    }

    /**
     * <p>
     * Create tuple from array. Array has to have exactly three elements.
     * </p>
     * 
     * @param <X> the array component type 
     * @param array the array to be converted to a tuple
     * @return the tuple
     */
    public static <X> Triplet<X,X,X> fromArray(final X[] array) {
        if (array == null) {
            throw new IllegalArgumentException("Array cannot be null");
        }
        if (array.length != 3) {
            throw new IllegalArgumentException("Array must have exactly 3 elements in order to create a Triplet. Size is " + array.length);
        }
        return new Triplet<X,X,X>(array[0],array[1],array[2]);
    }

    /**
     * <p>
     * Create tuple from collection. Collection has to have exactly three elements.
     * </p>
     * 
     * @param <X> the collection component type 
     * @param collection the collection to be converted to a tuple
     * @return the tuple
     */
    public static <X> Triplet<X,X,X> fromCollection(final Collection<X> collection) {
        return fromIterable(collection);
    }

    /**
     * <p>
     * Create tuple from iterable. Iterable has to have exactly three elements.
     * </p>
     * 
     * @param <X> the iterable component type 
     * @param iterable the iterable to be converted to a tuple
     * @return the tuple
     */
    public static <X> Triplet<X,X,X> fromIterable(final Iterable<X> iterable) {
        return fromIterable(iterable, 0, true);
    }

    /**
     * <p>
     * Create tuple from iterable, starting from the specified index. Iterable
     * can have more (or less) elements than the tuple to be created.
     * </p>
     * 
     * @param <X> the iterable component type 
     * @param iterable the iterable to be converted to a tuple
     * @return the tuple
     */
    public static <X> Triplet<X,X,X> fromIterable(final Iterable<X> iterable, int index) {
        return fromIterable(iterable, index, false);
    }

    private static <X> Triplet<X,X,X> fromIterable(final Iterable<X> iterable, int index, final boolean exactSize) {
        
        if (iterable == null) {
            throw new IllegalArgumentException("Iterable cannot be null");
        }

        boolean tooFewElements = false; 
        
        X element0 = null;
        X element1 = null;
        X element2 = null;
        
        final Iterator<X> iter = iterable.iterator();
        
        int i = 0;
        while (i < index) {
            if (iter.hasNext()) {
                iter.next();
            } else {
                tooFewElements = true;
            }
            i++;
        }
        
        if (iter.hasNext()) {
            element0 = iter.next();
        } else {
            tooFewElements = true;
        }
        
        if (iter.hasNext()) {
            element1 = iter.next();
        } else {
            tooFewElements = true;
        }
        
        if (iter.hasNext()) {
            element2 = iter.next();
        } else {
            tooFewElements = true;
        }
        
        if (tooFewElements && exactSize) {
            throw new IllegalArgumentException("Not enough elements for creating a Triplet (3 needed)");
        }
        
        if (iter.hasNext() && exactSize) {
            throw new IllegalArgumentException("Iterable must have exactly 3 available elements in order to create a Triplet.");
        }
        
        return new Triplet<X,X,X>(element0, element1, element2);
        
    }

    public Triplet(
            final A value0,
            final B value1,
            final C value2) {
        super(value0, value1, value2);
        this.val0 = value0;
        this.val1 = value1;
        this.val2 = value2;
    }

    public A getValue0() {
        return this.val0;
    }

    public B getValue1() {
        return this.val1;
    }

    public C getValue2() {
        return this.val2;
    }

    @Override
    public int getSize() {
        return SIZE;
    }

	/*
	 * ………………
	 * ………………
	 * ………………
	 */

}

自定义工具类
通过重载with方法,可以自动根据传入的参数个数,返回相应的元组对象

public class TupleUtils {

    public static <A> Unit<A> with(final A value0){
        return Unit.with(value0);
    }

    public static <A, B> Pair<A, B> with(final A value0, final B value1){
        return Pair.with(value0, value1);
    }

    public static <A, B, C> Triplet<A, B, C> with(final A value0, final B value1, final C value2){
        return Triplet.with(value0, value1, value2);
    }
}

使用案例
现有实体类Student、Teaccher、Programmer,需要存储实体类的字节码文件、对应数据库表的主键名称、对应数据库表的毕业院校字段名称

我们可以通过再定义一个类的方式实现,但是如果还要再添加其他属性的话,又得重新定义

如果采用元组的方式实现,就可以有效避免

public class TupleTest {

    public static void main(String[] args) {
        List<Triplet<Class, String, String>> roleList = new ArrayList<Triplet<Class, String, String>>();

        Triplet<Class, String, String> studentTriplet = TupleUtils.with(Student.class, "sid", "graduate");
        Triplet<Class, String, String> teacherTriplet = TupleUtils.with(Teacher.class, "sid", "graduate");
        Triplet<Class, String, String> programmerTriplet = TupleUtils.with(Programmer.class, "sid", "graduate");

        roleList.add(studentTriplet);
        roleList.add(teacherTriplet);
        roleList.add(programmerTriplet);

        for (Triplet<Class, String, String> triplet : roleList) {
            System.out.println(triplet);
        }
    }
}

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

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

相关文章

深入了解Netty,这一篇就够了

一、Netty简介 Netty是由JBOSS提供的一个java开源框架&#xff0c;现为 Github上的独立项目。Netty提供异步的、事件驱动的网络应用程序框架和工具&#xff0c;用以快速开发高性能、高可靠性的网络服务器和客户端程序。 也就是说&#xff0c;Netty 是一个基于NIO的客户、服务器…

微分方程(人口预测+传染病模型)

一、定义 微分方程&#xff1a;含导数或微分的方程 微分方程的阶数&#xff1a;所含导数或微分的最高阶数&#xff0c;如y’’’2y’’-2x0是三阶微分方程 微分方程的解&#xff1a;使得微分方程成立的函数 例如y’-2x0的解可以为x或者x1 微分方程的通解和特解&#xff1a;特…

【pat】分而治之【图】

分而治之&#xff0c;各个击破是兵家常用的策略之一。在战争中&#xff0c;我们希望首先攻下敌方的部分城市&#xff0c;使其剩余的城市变成孤立无援&#xff0c;然后再分头各个击破。为此参谋部提供了若干打击方案。本题就请你编写程序&#xff0c;判断每个方案的可行性。输入…

MySQL触发器相关知识

1、什么是触发器 触发器&#xff08;trigger&#xff09;是mysql的数据库对象之一&#xff0c;是一种与表操作有关的数据库对象&#xff0c;当触发器所在表上出现指定事件时&#xff08;这些事件包括insert、update、delete三种&#xff09;&#xff0c;将调用该对象&#xff0…

2023年安装Flutter开发环境_在C盘空间占用空间

2023年安装Flutter开发环境&#xff0c;C盘空间还剩多少&#xff1f; 1&#xff1a;Flutter开发对磁盘空间的要求 2&#xff1a;其余日常辅助软件安装D盘&#xff08;占用8GB&#xff09; 3&#xff1a;消耗时间&#xff08;3天–网络有时会中断&#xff09;–【劝退提示】 安…

Hudi(12):Hudi集成Flink之sql-client方式

目录 0. 相关文章链接 1. 启动sql-client 1.1. 修改flink-conf.yaml配置 1.2. local模式 1.3. yarn-session模式 2. 插入数据 3. 查询数据 4. 更新数据 5. 流式插入 5.1. 创建测试表 5.2. 执行插入 5.3. 查看job 5.4. 查看job 5.5. 查看HDFS目录 5.6. 查询结果 …

行为型模式 - 解释器模式Interpreter

学习而来&#xff0c;代码是自己敲的。也有些自己的理解在里边&#xff0c;有问题希望大家指出。 模式的定义与特点 解释器模式&#xff08;Interperter Pattern&#xff09;&#xff0c;给定一个语言&#xff0c;定义它的文法表示&#xff0c;并定义一个解释器&#xff0c;这个…

智引未来,深兰科技机器人家族首次亮相TechG

12月31日&#xff0c;首届上海国际消费电子技术展(简称TechG)在南京国际博览中心圆满落下帷幕。作为全球消费电子技术领域的顶级行业盛会&#xff0c;本届展会共吸引了来自全球的300余家企业出席&#xff0c;共计逾2万名专业人士到场参观。阿里巴巴、蚂蚁科技、海尔、科大讯飞、…

PyQt6快速入门-菜单与工具栏

菜单与工具栏 接下来我们将了解一些常见的用户界面元素,您可能在许多其他应用程序中都见过它们——工具栏和菜单。 我们还将介绍Qt 提供的用于最小化不同 UI 区域之间的重复的整洁系统 — QAction。 1、Toolbars 最常见的用户界面元素之一是工具栏。 工具栏是用于在应用程序…

【微服务】Nacos 账号权限体系

目录 一、背景 1、账号体系 2、账号实体映射 二、方案 1、Nacos 资源模型 2、Nacos 授权 resource 2.1、授权 resource 组成 2.2、不同级别授权资源组成 3、Nacos 授权 Opers 4、Nacos 具体权限定义 4.1、Opers 组成 4.2、具体实例 4.3、工程实现 三、RBAC 设计实…

IDEA使用Spring initializr 创建SpringBoot项目超时问题解决办法

1.问题描述 IDEA使用Spring initializr 创建SpringBoot项目时经常会出现连接超时的问题&#xff0c;报错提示如下 还有一个提示非常简短就是 connect timed out 总之问题都是一样&#xff0c;可能因为是外网所以有时候会出现连接问题&#xff0c;多试几次会成功&#xff0c;…

AutoScraper——爬虫神器

AutoScraper是一个自动化的爬虫工具&#xff0c;非常智能&#xff0c;而且使用简单便捷。AutoScraper 是使用 Python 实现的 Web 爬虫&#xff0c;兼容 Python 3&#xff0c;能快速且智能获取指定网站上的数据&#xff0c;在github上具有4.8K⭐️。github链接&#xff1a;https…

有哪些你看了以后大呼过瘾的计算机书籍?

推荐几本让程序员们爱不释手的经典书。 1、代码整洁之道 鲍勃大叔作品&#xff0c;程序员&#xff0c;汇聚编程数十年编程生涯的心得体会&#xff0c;阐释如何解决软件开发人员、项目经理及软件项目领导们所面临的棘手的问题。 本书提出一种观点&#xff1a;代码质量与其整洁…

Qt+C/C++文章小说人物关系分析

程序示例精选 QtC文章小说人物关系分析 如需安装运行环境或远程调试&#xff0c;见文章底部微信名片&#xff0c;由专业技术人员远程协助&#xff01; 前言 这篇博客针对<<QtC/C文章小说人物关系分析>>编写代码&#xff0c;代码整洁&#xff0c;规则&#xff0c;易…

浅谈未来跨境电商发展的新趋势?

从21世纪初&#xff0c;互联网在我国应运而生&#xff0c;并且在国家政策的倾斜和互联网的渗透下&#xff0c;结合互联网商业巨头对全球互联网产业的优化布局&#xff0c;互联网技术逐渐得到完善&#xff0c;伴随着近年来直播带货以及互联网电商的加持&#xff0c;我国的线上购…

Crack:dhtmlx JavaScript UI Libraries 商业企业版

dhtmlx JavaScript UI Libraries 企业版 包含Ω578867473&#xff1a; JS Gantt Chart JS Scheduler JS UI Widgets Library JS Diagram Library JS Kanban Board JS To Do List JS Event Calendar JS Spreadsheet JS Pivot Table JS File Uploader JS Rich Text Editor Gantt…

家庭库存管理系统Homebox

本文完成于 2022 年的 10 月&#xff0c; 最近正好有网友在找这方面的软件&#xff0c;就给翻出来了&#xff1b;Homebox 通过存储位置和标签两个维度来管理物品&#xff0c;非常简单易用&#xff0c;希望能满足要求&#xff1b; 什么是 Homebox &#xff1f; Homebox 是一个自…

TensorFlow和PyTorch的实际应用比较

TensorFlow和PyTorch是两个最受欢迎的开源深度学习框架&#xff0c;这两个框架都为构建和训练深度学习模型提供了广泛的功能&#xff0c;并已被研发社区广泛采用。但是作为用户&#xff0c;我们一直想知道哪种框架最适合我们自己特定项目&#xff0c;所以在本文与其他文章的特性…

我阳了,一针疫苗未打

12月31日凌晨两点&#xff0c;我被热醒&#xff0c;浑身湿透。身体发出强烈信号&#xff0c;本能地催促我赶紧喝水&#xff0c;再不喝&#xff0c;要炸。毫不犹豫地&#xff0c;我走进厨房&#xff0c;摁下电水壶&#xff0c;1.5L 水&#xff0c;90度。几杯水下肚&#xff0c;身…

2020年MathorCup高校数学建模挑战赛—大数据竞赛B题遥感图像地块分割与提取求解全过程文档及程序

2020年MathorCup高校数学建模挑战赛—大数据竞赛 B题 遥感图像地块分割与提取 原题再现&#xff1a; 耕地的数量和质量是保持农业可持续发展的关键&#xff0c;利用卫星遥感影像可以识别并提取耕地&#xff0c;并对耕地进行遥感制图&#xff0c;准确的耕地分布能够为国家决策…